From e2807eb59ad5b9e45311544278c905fd942e85b3 Mon Sep 17 00:00:00 2001 From: 243wresfdxvc Date: Sat, 23 Apr 2022 16:15:53 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200203.=E7=A7=BB=E5=87=BA?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=20C=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0203.移除链表元素.md | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index c34831b7..751553e2 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -145,6 +145,38 @@ public: ## 其他语言版本 C: +用原来的链表操作: +```c +struct ListNode* removeElements(struct ListNode* head, int val){ + struct ListNode* temp; + // 当头结点存在并且头结点的值等于val时 + while(head && head->val == val) { + temp = head; + // 将新的头结点设置为head->next并删除原来的头结点 + head = head->next; + free(temp); + } + + struct ListNode *cur = head; + // 当cur存在并且cur->next存在时 + // 此解法需要判断cur存在因为cur指向head。若head本身为NULL或者原链表中元素都为val的话,cur也会为NULL + while(cur && (temp = cur->next)) { + // 若cur->next的值等于val + if(temp->val == val) { + // 将cur->next设置为cur->next->next并删除cur->next + cur->next = temp->next; + free(temp); + } + // 若cur->next不等于val,则将cur后移一位 + else + cur = cur->next; + } + + // 返回头结点 + return head; +} +``` +设置一个虚拟头结点: ```c /** * Definition for singly-linked list.