📜  从给定的链表中删除总和为K的连续节点

📅  最后修改于: 2021-05-04 18:15:22             🧑  作者: Mango

给定一个单链表和一个整数K ,任务是从给定链表中删除总和为K的所有连续节点集。删除后打印更新的链表。如果无法进行此类删除,请打印原始的“链接”列表。

例子:

方法:

  1. 在链接列表的开头将Node的值附加为零。
  2. 遍历给定的链表。
  3. 在遍历期间,将节点值的总和一直存储到unordered_map中,该值与当前节点的引用有关。
  4. 如果unordered_map中存在具有值(sum – K)的节点,则从对应于存储在映射中的值(sum – K)的节点中删除所有节点到当前节点,并将总和更新为(sum – K)
  5. 如果在unordered_map中不存在带有值(总和– K)的节点,则将当前总和与节点一起存储在地图中。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// A Linked List Node
struct ListNode {
    int val;
    ListNode* next;
 
    // Contructor
    ListNode(int x)
        : val(x)
        , next(NULL)
    {
    }
};
 
// Function to create Node
ListNode* getNode(int data)
{
    ListNode* temp;
    temp = (ListNode*)malloc(sizeof(ListNode));
    temp->val = data;
    temp->next = NULL;
    return temp;
}
 
// Function to print the Linked List
void printList(ListNode* head)
{
    while (head->next) {
        cout << head->val << " -> ";
        head = head->next;
    }
    printf("%d", head->val);
}
 
// Function that removes continuos nodes
// whose sum is K
ListNode* removeZeroSum(ListNode* head, int K)
{
    // Root node initialise to 0
    ListNode* root = new ListNode(0);
 
    // Append at the front of the given
    // Linked List
    root->next = head;
 
    // Map to store the sum and reference
    // of the Node
    unordered_map umap;
 
    umap[0] = root;
 
    // To store the sum while traversing
    int sum = 0;
 
    // Traversing the Linked List
    while (head != NULL) {
 
        // Find sum
        sum += head->val;
 
        // If found value with (sum - K)
        if (umap.find(sum - K) != umap.end()) {
 
            ListNode* prev = umap[sum - K];
            ListNode* start = prev;
 
            // Delete all the node
            // traverse till current node
            int aux = sum;
 
            // Update sum
            sum = sum - K;
 
            // Traverse till current head
            while (prev != head) {
                prev = prev->next;
                aux += prev->val;
                if (prev != head) {
                    umap.erase(aux);
                }
            }
 
            // Update the start value to
            // the next value of current head
            start->next = head->next;
        }
 
        // If (sum - K) value not found
        else if (umap.find(sum) == umap.end()) {
            umap[sum] = head;
        }
 
        head = head->next;
    }
 
    // Return the value of updated
    // head node
    return root->next;
}
 
// Driver Code
int main()
{
    // head Node
    ListNode* head;
 
    // Create Linked List
    head = getNode(1);
    head->next = getNode(2);
    head->next->next = getNode(-3);
    head->next->next->next = getNode(3);
    head->next->next->next->next = getNode(1);
 
    // Given sum K
    int K = 5;
 
    // Function call to get head node
    // of the updated Linked List
    head = removeZeroSum(head, K);
 
    // Print the updated Linked List
    if (head != NULL)
        printList(head);
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
// A Linked List Node
class ListNode {
    int val;
    ListNode next;
 
    // Contructor
    ListNode(int val)
    {
        this.val = val;
        this.next = null;
    }
}
 
class GFG {
 
    // Function to create Node
    static ListNode getNode(int data)
    {
        ListNode temp = new ListNode(data);
        return temp;
    }
 
    // Function to print the Linked List
    static void printList(ListNode head)
    {
        while (head.next != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.print(head.val);
    }
 
    // Function that removes continuos nodes
    // whose sum is K
    static ListNode removeZeroSum(ListNode head, int K)
    {
        // Root node initialise to 0
        ListNode root = new ListNode(0);
 
        // Append at the front of the given
        // Linked List
        root.next = head;
 
        // Map to store the sum and reference
        // of the Node
        Map umap
            = new HashMap();
 
        umap.put(0, root);
 
        // To store the sum while traversing
        int sum = 0;
 
        // Traversing the Linked List
        while (head != null) {
 
            // Find sum
            sum += head.val;
 
            // If found value with (sum - K)
            if (umap.containsKey(sum - K)) {
 
                ListNode prev = umap.get(sum - K);
                ListNode start = prev;
 
                // Delete all the node
                // traverse till current node
                int aux = sum;
 
                // Update sum
                sum = sum - K;
 
                // Traverse till current head
                while (prev != head) {
                    prev = prev.next;
                    aux += prev.val;
                    if (prev != head) {
                        umap.remove(aux);
                    }
                }
 
                // Update the start value to
                // the next value of current head
                start.next = head.next;
            }
 
            // If (sum - K) value not found
            else if (!umap.containsKey(sum)) {
                umap.put(sum, head);
            }
 
            head = head.next;
        }
 
        // Return the value of updated
        // head node
        return root.next;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // head Node
        ListNode head;
 
        // Create Linked List
        head = getNode(1);
        head.next = getNode(2);
        head.next.next = getNode(-3);
        head.next.next.next = getNode(3);
        head.next.next.next.next = getNode(1);
 
        // Given sum K
        int K = 5;
 
        // Function call to get head node
        // of the updated Linked List
        head = removeZeroSum(head, K);
 
        // Print the updated Linked List
        if (head != null)
            printList(head);
    }
}
 
// This code is contributed by jitin.


Python3
# Python3 program for the above approach
 
# A Linked List Node
class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
 
# Function to create Node
def getNode(data):
    temp = ListNode(data)
    temp.next = None
    return temp
 
# Function to print the Linked List
def printList(head):
    while (head.next):
        print(head.val, end=' -> ')
        head = head.next
    print(head.val, end='')
 
# Function that removes continuos nodes
# whose sum is K
def removeZeroSum(head, K):
 
    # Root node initialise to 0
    root = ListNode(0)
 
    # Append at the front of the given
    # Linked List
    root.next = head
 
    # Map to store the sum and reference
    # of the Node
    umap = dict()
 
    umap[0] = root
 
    # To store the sum while traversing
    sum = 0
 
    # Traversing the Linked List
    while (head != None):
 
        # Find sum
        sum += head.val
 
        # If found value with (sum - K)
        if ((sum - K) in umap):
 
            prev = umap[sum - K]
            start = prev
 
            # Delete all the node
            # traverse till current node
            aux = sum
 
            # Update sum
            sum = sum - K
 
            # Traverse till current head
            while (prev != head):
                prev = prev.next
                aux += prev.val
                if (prev != head):
                    umap.remove(aux)
 
            # Update the start value to
            # the next value of current head
            start.next = head.next
 
        # If (sum - K) value not found
        else:
            umap[sum] = head
 
        head = head.next
 
    # Return the value of updated
    # head node
    return root.next
 
 
# Driver Code
if __name__ == '__main__':
 
    # Create Linked List
    head = getNode(1)
    head.next = getNode(2)
    head.next.next = getNode(-3)
    head.next.next.next = getNode(3)
    head.next.next.next.next = getNode(1)
 
    # Given sum K
    K = 5
 
    # Function call to get head node
    # of the updated Linked List
    head = removeZeroSum(head, K)
 
    # Print the updated Linked List
    if(head != None):
        printList(head)
 
    # This code is contributed by pratham76


C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
// A Linked List Node
class ListNode {
    public int val;
    public ListNode next;
 
    // Contructor
    public ListNode(int val)
    {
        this.val = val;
        this.next = null;
    }
}
 
class GFG {
 
    // Function to create Node
    static ListNode getNode(int data)
    {
        ListNode temp = new ListNode(data);
        return temp;
    }
 
    // Function to print the Linked List
    static void printList(ListNode head)
    {
        while (head.next != null) {
            Console.Write(head.val + " -> ");
            head = head.next;
        }
        Console.Write(head.val);
    }
 
    // Function that removes continuos nodes
    // whose sum is K
    static ListNode removeZeroSum(ListNode head, int K)
    {
 
        // Root node initialise to 0
        ListNode root = new ListNode(0);
 
        // Append at the front of the given
        // Linked List
        root.next = head;
 
        // Map to store the sum and reference
        // of the Node
        Dictionary umap
            = new Dictionary();
 
        umap.Add(0, root);
 
        // To store the sum while traversing
        int sum = 0;
 
        // Traversing the Linked List
        while (head != null) {
 
            // Find sum
            sum += head.val;
 
            // If found value with (sum - K)
            if (umap.ContainsKey(sum - K)) {
                ListNode prev = umap[sum - K];
                ListNode start = prev;
 
                // Delete all the node
                // traverse till current node
                int aux = sum;
 
                // Update sum
                sum = sum - K;
 
                // Traverse till current head
                while (prev != head) {
                    prev = prev.next;
                    aux += prev.val;
 
                    if (prev != head) {
                        umap.Remove(aux);
                    }
                }
 
                // Update the start value to
                // the next value of current head
                start.next = head.next;
            }
 
            // If (sum - K) value not found
            else if (!umap.ContainsKey(sum)) {
                umap.Add(sum, head);
            }
 
            head = head.next;
        }
 
        // Return the value of updated
        // head node
        return root.next;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
 
        // head Node
        ListNode head;
 
        // Create Linked List
        head = getNode(1);
        head.next = getNode(2);
        head.next.next = getNode(-3);
        head.next.next.next = getNode(3);
        head.next.next.next.next = getNode(1);
 
        // Given sum K
        int K = 5;
 
        // Function call to get head node
        // of the updated Linked List
        head = removeZeroSum(head, K);
 
        // Print the updated Linked List
        if (head != null)
            printList(head);
    }
}
 
// This code is contributed by rutvik_56


输出:
1 -> 2 -> -3 -> 3 -> 1

时间复杂度: O(N) ,其中N是链接列表中Node的数量。
辅助空间复杂度: O(N) ,其中N是链表中节点的数量。