添加 0203.移出链表元素.md C语言解法

This commit is contained in:
243wresfdxvc
2022-04-23 16:15:53 +00:00
parent 3feae289d9
commit e2807eb59a

View File

@ -145,6 +145,38 @@ public:
## 其他语言版本 ## 其他语言版本
C: 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 ```c
/** /**
* Definition for singly-linked list. * Definition for singly-linked list.