mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 203. Remove Linked List Elements.md
This commit is contained in:
parent
89ca6c5c77
commit
9f5390f7a2
40
203. Remove Linked List Elements.md
Normal file
40
203. Remove Linked List Elements.md
Normal file
@ -0,0 +1,40 @@
|
||||
# [203. Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/)
|
||||
# 思路
|
||||
删除链表中值满足条件的节点,常规操作。
|
||||
设两个指针pre和p,p为工作指针,pre为p的前一个节点,判断p的值是否为val:
|
||||
* 若是,将pre的next指向p的next,再删除节点p;
|
||||
* 若不是,将pre指向p即可。
|
||||
|
||||
最后将p指向pre的next。
|
||||
为了操作方便,可以设置一个头结点。
|
||||
# C++
|
||||
```
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* struct ListNode {
|
||||
* int val;
|
||||
* ListNode *next;
|
||||
* ListNode(int x) : val(x), next(NULL) {}
|
||||
* };
|
||||
*/
|
||||
class Solution {
|
||||
public:
|
||||
ListNode* removeElements(ListNode* head, int val) {
|
||||
ListNode *list_head = new ListNode(0); // 设一个头结点便于操作
|
||||
list_head -> next = head;
|
||||
ListNode *pre = list_head, *p = head, *target;
|
||||
|
||||
while(p){
|
||||
if(p -> val == val){
|
||||
target = p;
|
||||
pre -> next = p -> next;
|
||||
target -> next = NULL;
|
||||
delete target;
|
||||
}
|
||||
else pre = p;
|
||||
p = pre -> next;
|
||||
}
|
||||
return list_head -> next;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user