LeetCode/203. Remove Linked List Elements.md
2018-09-22 18:45:34 +08:00

41 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [203. Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/description/)
# 思路
删除链表中值满足条件的节点,常规操作。
设两个指针pre和pp为工作指针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;
}
};
```