【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]

Constraints:

  • The given linked list will contain between 1 and 1000 nodes.
  • Each node in the linked list has -1000 <= node.val <= 1000.

解题思路:方法比较简单,可以从头开始遍历链表,并累加每一个节点的和,遇到和为零或者与之前出现过的和相同的情况则表示这一段可以删除,删除后又重头开始遍历链表,直到找不到可以删除的段为止。至于怎么删除链表的中一段,我的方法是用一个list保存链表的所有节点,删除的时候直接删除list的元素。全部删除完成后再将list的剩余元素组成新链表即可。

代码如下:

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def removeZeroSumSublists(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        node_list = []
        node = head
        while node != None:
            node_list.append(node)
            node = node.next

        flag = True
        while flag:
            flag = False
            dic = {}
            amount = 0
            for inx,item in enumerate(node_list):
                amount += item.val
                if amount == 0:
                    node_list = node_list[inx+1:]
                    flag = True
                    break
                elif amount in dic:
                    node_list = node_list[:dic[amount] + 1] + node_list[inx + 1:]
                    flag = True
                    break
                dic[amount] = inx
        if len(node_list) == 0:
            return None
        for i in range(len(node_list)-1):
            node_list[i].next = node_list[i+1]
        node_list[-1].next = None
        head = node_list[0]
        return head

猜你喜欢

转载自www.cnblogs.com/seyjs/p/11440723.html