Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e2807eb

Browse files
添加 0203.移出链表元素.md C语言解法
1 parent 3feae28 commit e2807eb

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎problems/0203.移除链表元素.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,38 @@ public:
145145
146146
## 其他语言版本
147147
C:
148+
用原来的链表操作:
149+
```c
150+
struct ListNode* removeElements(struct ListNode* head, int val){
151+
struct ListNode* temp;
152+
// 当头结点存在并且头结点的值等于val时
153+
while(head && head->val == val) {
154+
temp = head;
155+
// 将新的头结点设置为head->next并删除原来的头结点
156+
head = head->next;
157+
free(temp);
158+
}
159+
160+
struct ListNode *cur = head;
161+
// 当cur存在并且cur->next存在时
162+
// 此解法需要判断cur存在因为cur指向head。若head本身为NULL或者原链表中元素都为val的话,cur也会为NULL
163+
while(cur && (temp = cur->next)) {
164+
// 若cur->next的值等于val
165+
if(temp->val == val) {
166+
// 将cur->next设置为cur->next->next并删除cur->next
167+
cur->next = temp->next;
168+
free(temp);
169+
}
170+
// 若cur->next不等于val,则将cur后移一位
171+
else
172+
cur = cur->next;
173+
}
174+
175+
// 返回头结点
176+
return head;
177+
}
178+
```
179+
设置一个虚拟头结点:
148180
```c
149181
/**
150182
* Definition for singly-linked list.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /