1. 程式人生 > 實用技巧 >203.移除連結串列元素

203.移除連結串列元素

題目描述

刪除連結串列中等於給定值val的所有節點。

示例:

輸入: 1->2->6->3->4->5->6, val = 6
輸出: 1->2->3->4->5

注意點

1、刪除點在開頭;

2、刪除點在結尾;

3、連續刪除兩個位置;

4、需delete手動釋放記憶體;

頭結點命中處理

1、頭結點命中特殊處理;

2、引入虛擬頭結點;

刪除操作

1、兩個指標完成刪除;

2、一個指標完成刪除;

方法一

頭結點命中特殊處理,利用兩個指標完成刪除操作;

/**
 * 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 *p = head;
    	ListNode *pre = p;
    	while( p )
    	{
    		if( p->val == val )
    		{
    			if( pre == p )
    			{
    				head = head->next;
    				p = head;
    				pre = p;
    			}
    			else
                {
                	pre->next = p->next;
                	p = p->next;
                }
    		}
    		else
    		{
    			pre = p;
    			p = p->next;
    		}
    	}

    	return head;
    }
};

  

 

方法二

引入虛擬頭結點,利用兩個指標完成刪除操作;

/**
 * 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 *res = new ListNode(0);
    	ListNode *p = head;
    	res->next = head;
    	ListNode *pre = res;
    	while( p )
    	{
    		if( p->val == val )
    			pre->next = p->next;
    		else
    			pre = p;
    		p = p->next;
    	}

    	return res->next;
    }
};

  

方法三

引入虛擬頭結點,一個指標完成刪除;

/**
 * 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 *res = new ListNode(0);
    	res->next = head;
        ListNode *p = res;

    	while( p->next )
    	{
    		if( p->next->val == val )
    		{
    			ListNode *tmp = p->next;
    			p->next = p->next->next;
    			delete tmp;
    		}
    		else
    			p = p->next;
    	}

    	return res->next;
    }
};