[LeetCode]1171. Remove Zero Sum Consecutive Nodes from Linked List

一、題意

Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

After doing so, return the head of the final linked list.  You may return any such answer.

(Note that in the examples below, all sequences are serializations of ListNode objects.)

二、樣例

Example 1:

Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.

Example 2:

Input: head = [1,2,3,-3,4]
Output: [1,2,4]

Example 3:

Input: head = [1,2,3,-3,-2]
Output: [1]

三、題解

題目大意是:給出一個鏈表,刪除和爲0的子序列,直到鏈表中沒有和爲0的子序列。

例如:輸入爲[1,2,-3,3,1],其中1+2+(-3) = 0那麼久刪除節點1、2、-3(當然也可以刪除-3、3)。

思路:從第一個節點開始遍歷,不斷計算以該節點爲首的鏈表的和,如果存在等於0的情況,那麼刪除這些節點。當然若該節點就等於0,直接刪除該節點。

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    
    
    ListNode* deleteNode(ListNode* node, ListNode* &head){
        if(head == node){
            head = head->next;
            return head;
        }
        
        ListNode* temp = head;
        ListNode* tempnext = head->next;
        
        while(tempnext!=NULL){
            if(tempnext == node){
                temp->next = tempnext->next;
                break;
            }else{
                temp = temp->next;
                tempnext = tempnext->next;
            }
        }
        return temp->next;
    }
    
    ListNode* removeZeroSumSublists(ListNode* head) {
        if(head == NULL){
            return NULL;
        }
        
        ListNode* first = new ListNode(-1);//增加first節點,便於刪除節點
        first->next = head;
        ListNode* p = head;//遍歷的節點
        ListNode* pp = first;//被遍歷的節點的父節點,便於刪除節點
        
        while(p!=NULL){
            if(p->val == 0){//若節點val爲0,那麼直接刪除該節點,同時p指向p->next,同時必須保證如果刪除的是head,first->next也要相應改變
                p = deleteNode(p, first->next);
            }else{
                int sum = 0;
                int f = 1;
                ListNode* temp = p;//以p節點爲首,往後遍歷,看是否存在節點temp,p與temp之間的節點之和爲0
                while(temp!=NULL){
                    sum += temp->val;
                    if(sum == 0){//若存在,那麼刪除[p,temp]節點
                        //cout<<pp->val<<" "<<temp->val<<endl;
                        pp->next = temp->next;
                        p = temp->next;
                        f = 0;
                        break;
                    }else{
                        temp = temp->next;
                    }
                }
                
                if(f==1){//若不存在,開始遍歷p->next
                    pp = p;
                    p = p->next;
                }
            }
        }
        return first->next;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章