203. Remove Linked List Elements(简单)
Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
思路:
-
添加哑节点来避免需要判断head是否为NULL;然后遍历链表,找到待删节点的前驱节点,和后继节点,将后继节点链接到前驱节点上即可。
-
C++
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* newhead = new ListNode();
ListNode* p = newhead;
p->next = head;
ListNode* prec = p;
while(p!=nullptr ){
if(p->val == val){
prec->next = p->next;
p = prec->next;
}
else{
prec = p;
p = p->next;
}
}
return newhead->next;
// ListNode* p = new ListNode(0, head);
// ListNode* newhead = p;
// while(p->next!=nullptr){
// if(p->next->val== val){
// ListNode* temp = p->next;
// p->next = p->next->next;
// delete temp;
// }
// else{
// p = p->next;
// }
// }
// head = newhead->next;
// delete newhead;
// return head;
}
};
- python
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
newhead = ListNode(0,head)
p = newhead
prec = p
while(p!=None):
if p.val == val:
prec.next = p.next
p = prec.next
else:
prec = p
p = p.next
return newhead.next