[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;
    }
};

 

posted on 2019-08-26 21:45  刘好念  阅读(1)  评论(0编辑  收藏  举报  来源