1171. Remove Zero Sum Consecutive Nodes from Linked List

/**
1171. Remove Zero Sum Consecutive Nodes from Linked List
https://leetcode.com/problems/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:
1. The given linked list will contain between 1 and 1000 nodes.
2. Each node in the linked list has -1000 <= node.val <= 1000.
*/
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

//
impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val,
        }
    }
}

pub struct Solution {}

impl Solution {
    /*
    solution: bruce force, keep tracking consecutive sequences for each node, check if sum up is 0;
    Time:O(n^2), Space:O(n)
    */
    pub fn remove_zero_sum_sublists(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut vec = Self::node_to_vec(head);
        let size = vec.len();
        for mut i in 0..size {
            let mut sum = 0;
            for j in i..size {
                sum += vec[j];
                if (sum == 0) {
                    for k in i..j + 1 {
                        //replace the element to 0 if the index between i and j
                        std::mem::replace(&mut vec[k], 0);
                    }
                    i = j;
                }
            }
        }
        let mut res = Vec::new();
        for i in 0..size {
            if (vec[i] != 0) {
                res.push(vec[i])
            }
        }
        Self::vec_to_node(res)
    }

    fn vec_to_node(vec: Vec<i32>) -> Option<Box<ListNode>> {
        let mut node = None;
        let size = vec.len();
        for i in (0..size).rev() {
            node = Some(Box::new(ListNode { val: vec[i], next: node }));
        }
        node
    }

    fn node_to_vec(head: Option<Box<ListNode>>) -> Vec<i32> {
        let mut vec = Vec::new();
        let mut p = &head;
        while let Some(node) = p {
            vec.push(node.val);
            p = &node.next;
        }
        vec
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/15425972.html