Categories
木有技术

LeetCode 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

思路:

思路很简单,记录当前指针的前一个节点,然后val对上的话把前一个节点的next指针指向当前节点的next指针。有几个需要注意的输入:

  1. 空指针输入,即head就是NULL
  2. head->val等于val的情况,即删除完后head指针会变化
  3. 末尾节点要删除的情况
  4. 删完之后链表变空的情况

《剑指Offer》这书还挺有用的,代码的稳健性很重要。

代码

/**
 * 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) {
        if(head == NULL)
            return head;
        ListNode* pNewHead = head;
        ListNode* pPrev = NULL;
        ListNode* pCurr = head;
        while(pCurr != NULL){
            if(pCurr->val == val){
                if(pPrev == NULL) {//pCurr is the head of linkedlist
                    pNewHead = pCurr->next;
                } else {
                    pPrev->next = pCurr->next;
                }
            } else {
                pPrev = pCurr;
            }
            pCurr = pCurr->next;
        }
        return pNewHead;
    }
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.