From e9202bcb5f6ca8150fcea99257520fc0053c03f4 Mon Sep 17 00:00:00 2001 From: ayuan <56953954+Ayuan66@users.noreply.github.com> Date: Tue, 3 Jan 2023 17:02:54 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=A8=E6=95=B0=E7=BB=84=E4=B8=8E?= =?UTF-8?q?=E9=93=BE=E8=A1=A8/=E9=93=BE=E8=A1=A8=EF=BC=88LinkedList?= =?UTF-8?q?=EF=BC=89=E4=B8=ADC=E8=AF=AD=E8=A8=80=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../linked_list.md | 69 +++++++++++++++++-- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/docs/chapter_array_and_linkedlist/linked_list.md b/docs/chapter_array_and_linkedlist/linked_list.md index 5b6888c06..1e1270158 100644 --- a/docs/chapter_array_and_linkedlist/linked_list.md +++ b/docs/chapter_array_and_linkedlist/linked_list.md @@ -97,7 +97,11 @@ comments: true === "C" ```c title="" - + /* 链表结点结构体 */ + typedef struct ListNode { + int val; // 结点值 + struct ListNode *next; // 指向下一结点的指针(引用) + }ListNode; ``` === "C#" @@ -226,7 +230,25 @@ comments: true === "C" ```c title="" + /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ + // 初始化各个结点 + ListNode* n0 = (ListNode*) malloc(sizeof(ListNode)); + ListNode* n1 = (ListNode*) malloc(sizeof(ListNode)); + ListNode* n2 = (ListNode*) malloc(sizeof(ListNode)); + ListNode* n3 = (ListNode*) malloc(sizeof(ListNode)); + ListNode* n4 = (ListNode*) malloc(sizeof(ListNode)); + n0->val = 1; + n1->val = 3; + n2->val = 2; + n3->val = 5; + n4->val = 4; + + // 构建引用指向 + n0->next = n1; + n1->next = n2; + n2->next = n3; + n3->next = n4; ``` === "C#" @@ -384,7 +406,24 @@ comments: true === "C" ```c title="" + /* 在链表的结点 n0 之后插入结点 P */ + void insert(ListNode* n0, ListNode* P) { + ListNode* n1 = n0->next; + n0->next = P; + P->next = n1; + } + /* 删除链表的结点 n0 之后的首个结点 */ + void remove(ListNode* n0) { + if (n0->next == NULL) + return; + // n0 -> P -> n1 + ListNode* P = n0->next; + ListNode* n1 = P->next; + n0->next = n1; + // 释放内存 + free(P) ; +} ``` === "C#" @@ -501,7 +540,15 @@ comments: true === "C" ```c title="" - + /* 访问链表中索引为 index 的结点 */ + ListNode* access(ListNode* head, int index) { + for (int i = 0; i < index; i++) { + head = head->next; + if (head == NULL) + return NULL; + } + return head; + } ``` === "C#" @@ -626,7 +673,17 @@ comments: true === "C" ```c title="" - + /* 在链表中查找值为 target 的首个结点 */ + int find(ListNode* head, int target) { + int index = 0; + while (head != NULL) { + if (head->val == target) + return index; + head = head->next; + index++; + } + return -1; + } ``` === "C#" @@ -745,7 +802,11 @@ comments: true === "C" ```c title="" - + typedef struct ListNode { + int val; + struct ListNode *next; + struct ListNode *prev; + }ListNode; ``` === "C#"