Skip to content

Latest commit

 

History

History
40 lines (38 loc) · 1.18 KB

203. Remove Linked List Elements.md

File metadata and controls

40 lines (38 loc) · 1.18 KB

思路

删除链表中值满足条件的节点,常规操作。
设两个指针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;
    }
};