📜  将给定的数字添加到存储在链表中的数字

📅  最后修改于: 2022-05-13 01:57:44.192000             🧑  作者: Mango

将给定的数字添加到存储在链表中的数字

给定一个表示整数的链表,如果表示的整数,则每个节点都是一个数字。任务是将给定的数字N添加到表示的整数。

例子:

方法:本文已经讨论了将存储在链表中的数字加1的方法,但是代码需要反转链表。
在这篇文章中,我们将问题扩展到将任何数字添加到存储在链表中的数字,并在不使用反转或递归的情况下实现相同的效果。



这个想法是遍历链表,并在遍历过程中维护一个指向最后一个值小于 9 的节点的指针。这是因为我们将一个数字添加到存储在链表中的数字上。因此,进位的最大值(如果存在)可以是1 。假设我们开始从最低有效数字向最高有效数字传播进位,那么一旦发现小于 9 的数字,传播就会停止。

以这种方式完整遍历链表后,我们终于到达了链表的最后一个节点,并且还维护了一个指向值小于9的最新节点的指针。
可能出现两种情况:

  1. 将最后一位数字相加后可能会溢出,即节点处的值大于 9。
  2. 没有溢出,即在节点处添加值后小于 10。

在第一种情况下,我们必须将进位从值小于 9 的最新节点传播到最后一个节点。
在第二种情况下,我们不需要做任何其他事情。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Node structure containing data
// and pointer to the next Node
struct node {
 
    int key;
    node* next;
 
    node(int n)
    {
        key = n;
        next = NULL;
    }
};
 
// Linked list class
class LinkedList {
 
    node* head;
 
public:
    // Default constructor for
    // creating empty list
    LinkedList();
 
    // Insert a node in linked list
    void insert(node* n);
 
    // Adding a single digit to the list
    void addDigit(int n);
 
    // Print the linked list
    void printList();
};
 
LinkedList::LinkedList()
{
    // Empty List
    head = NULL;
}
 
// Function to insert a node at the
// head of the linked list
void LinkedList::insert(node* n)
{
    // Empty List
    if (head == NULL)
        head = n;
 
    // Insert in the beginning of the list
    else {
        n->next = head;
        head = n;
    }
}
 
// Function to print the linked list
void LinkedList::printList()
{
    node* ptr = head;
 
    while (ptr) {
        cout << ptr->key << " -> ";
        ptr = ptr->next;
    }
    cout << "NULL" << endl;
}
 
// Function to add a digit to the integer
// represented as a linked list
void LinkedList::addDigit(int n)
{
 
    // To keep track of the last node
    // whose value is less than 9
    node* lastNode = NULL;
    node* curr = head;
 
    while (curr->next) {
 
        // If found a node with value
        // less than 9
        if (curr->key < 9)
            lastNode = curr;
 
        // Otherwise keep traversing
        // the list till end
        curr = curr->next;
    }
 
    // Add the given digit to the last node
    curr->key = curr->key + n;
 
    // In case of overflow in the last node
    if (curr->key > 9) {
 
        curr->key = curr->key % 10;
 
        // If the list is of the
        // form 9 -> 9 -> 9 -> ...
        if (lastNode == NULL) {
 
            // Insert a node at the beginning as
            // there would be overflow in the
            // head in this case
            insert(new node(1));
 
            // Adjust the lastNode pointer to
            // propagate the carry effect to
            // all the nodes of the list
            lastNode = head->next;
        }
 
        // Forward propagate carry effect
        while (lastNode != curr) {
            lastNode->key = (lastNode->key + 1) % 10;
            lastNode = lastNode->next;
        }
    }
}
 
// Driver code
int main()
{
    // Creating the linked list
    LinkedList* l1 = new LinkedList();
 
    // Adding elements to the linked list
    l1->insert(new node(9));
    l1->insert(new node(9));
    l1->insert(new node(1));
 
    // Printing the original list
    l1->printList();
 
    // Adding the digit
    l1->addDigit(5);
 
    // Printing the modified list
    l1->printList();
 
    return 0;
}


Java
// Java implementation of the approach
 
// Node structure containing data
// and pointer to the next Node
class node
{
    int key;
    node next;
 
    node(int n)
    {
        key = n;
        next = null;
    }
};
 
// Linked list class
class LinkedList
{
    static node head;
 
    // Default constructor for
    // creating empty list
    public LinkedList()
    {
        // Empty List
        head = null;
    }
 
    // Function to insert a node at the
    // head of the linked list
    void insert(node n)
    {
         
        // Empty List
        if (head == null)
            head = n;
 
        // Insert in the beginning of the list
        else
        {
            n.next = head;
            head = n;
        }
    }
 
    // Function to print the linked list
    void printList()
    {
        node ptr = head;
 
        while (ptr != null)
        {
            System.out.print(ptr.key + "->");
            ptr = ptr.next;
        }
        System.out.print("null" + "\n");
    }
 
    // Function to add a digit to the integer
    // represented as a linked list
    void addDigit(int n)
    {
 
        // To keep track of the last node
        // whose value is less than 9
        node lastNode = null;
        node curr = head;
 
        while (curr.next != null)
        {
 
            // If found a node with value
            // less than 9
            if (curr.key < 9)
                lastNode = curr;
 
            // Otherwise keep traversing
            // the list till end
            curr = curr.next;
        }
 
        // Add the given digit to the last node
        curr.key = curr.key + n;
 
        // In case of overflow in the last node
        if (curr.key > 9)
        {
            curr.key = curr.key % 10;
 
            // If the list is of the
            // form 9.9.9....
            if (lastNode == null)
            {
 
                // Insert a node at the beginning as
                // there would be overflow in the
                // head in this case
                insert(new node(1));
 
                // Adjust the lastNode pointer to
                // propagate the carry effect to
                // all the nodes of the list
                lastNode = head.next;
            }
 
            // Forward propagate carry effect
            while (lastNode != curr)
            {
                lastNode.key = (lastNode.key + 1) % 10;
                lastNode = lastNode.next;
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
         
        // Creating the linked list
        LinkedList l1 = new LinkedList();
 
        // Adding elements to the linked list
        l1.insert(new node(9));
        l1.insert(new node(9));
        l1.insert(new node(1));
 
        // Printing the original list
        l1.printList();
 
        // Adding the digit
        l1.addDigit(5);
 
        // Printing the modified list
        l1.printList();
    }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Node structure containing data
# and pointer to the next Node
class node:
 
    def __init__(self, key):
 
        self.key = key
        self.next = None
 
# Linked list class
class LinkedList:
 
    def __init__(self):
         
        self.head = None
 
    # Function to insert a node at the
    # head of the linked list
    def insert(self, n):
 
        # Empty List
        if (self.head == None):
            self.head = n
 
        # Insert in the beginning of the list
        else:
            n.next = self.head;
            self.head = n
 
    # Function to print the linked list
    def printList(self):
 
        ptr = self.head
 
        while (ptr != None):
            print(ptr.key, end = ' -> ')
            ptr = ptr.next
             
        print('NULL')
        
    # Function to add a digit to the integer
    # represented as a linked list
    def addDigit(self, n):
     
        # To keep track of the last node
        # whose value is less than 9
        lastNode = None
        curr = self.head
     
        while (curr.next != None):
         
            # If found a node with value
            # less than 9
            if (curr.key < 9):
                lastNode = curr
     
            # Otherwise keep traversing
            # the list till end
            curr = curr.next
     
        # Add the given digit to the last node
        curr.key = curr.key + n
     
        # In case of overflow in the last node
        if (curr.key > 9):
            curr.key = curr.key % 10
     
            # If the list is of the
            # form 9 . 9 . 9 . ...
            if (lastNode == None):
             
                # Insert a node at the beginning as
                # there would be overflow in the
                # self.head in this case
                self.insert(node(1))
     
                # Adjust the lastNode pointer to
                # propagate the carry effect to
                # all the nodes of the list
                lastNode = self.head.next
     
            # Forward propagate carry effect
            while (lastNode != curr):
                lastNode.key = (lastNode.key + 1) % 10
                lastNode = lastNode.next
             
# Driver code
if __name__=='__main__':
     
    # Creating the linked list
    l1 = LinkedList()
  
    # Adding elements to the linked list
    l1.insert(node(9))
    l1.insert(node(9))
    l1.insert(node(1))
  
    # Printing the original list
    l1.printList()
  
    # Adding the digit
    l1.addDigit(5)
  
    # Printing the modified list
    l1.printList()
  
# This code is contributed by rutvik_56


C#
// C# implementation of the approach
using System;
 
// Node structure containing data
// and pointer to the next Node
public class node
{
    public int key;
    public node next;
 
    public node(int n)
    {
        key = n;
        next = null;
    }
};
 
// Linked list class
public class List
{
    static node head;
 
    // Default constructor for
    // creating empty list
    public List()
    {
        // Empty List
        head = null;
    }
 
    // Function to insert a node at the
    // head of the linked list
    void insert(node n)
    {
         
        // Empty List
        if (head == null)
            head = n;
 
        // Insert in the beginning of the list
        else
        {
            n.next = head;
            head = n;
        }
    }
 
    // Function to print the linked list
    void printList()
    {
        node ptr = head;
 
        while (ptr != null)
        {
            Console.Write(ptr.key + "->");
            ptr = ptr.next;
        }
        Console.Write("null" + "\n");
    }
 
    // Function to add a digit to the integer
    // represented as a linked list
    void addDigit(int n)
    {
 
        // To keep track of the last node
        // whose value is less than 9
        node lastNode = null;
        node curr = head;
 
        while (curr.next != null)
        {
 
            // If found a node with value
            // less than 9
            if (curr.key < 9)
                lastNode = curr;
 
            // Otherwise keep traversing
            // the list till end
            curr = curr.next;
        }
 
        // Add the given digit to the last node
        curr.key = curr.key + n;
 
        // In case of overflow in the last node
        if (curr.key > 9)
        {
            curr.key = curr.key % 10;
 
            // If the list is of the
            // form 9.9.9....
            if (lastNode == null)
            {
 
                // Insert a node at the beginning as
                // there would be overflow in the
                // head in this case
                insert(new node(1));
 
                // Adjust the lastNode pointer to
                // propagate the carry effect to
                // all the nodes of the list
                lastNode = head.next;
            }
 
            // Forward propagate carry effect
            while (lastNode != curr)
            {
                lastNode.key = (lastNode.key + 1) % 10;
                lastNode = lastNode.next;
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
         
        // Creating the linked list
        List l1 = new List();
 
        // Adding elements to the linked list
        l1.insert(new node(9));
        l1.insert(new node(9));
        l1.insert(new node(1));
 
        // Printing the original list
        l1.printList();
 
        // Adding the digit
        l1.addDigit(5);
 
        // Printing the modified list
        l1.printList();
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
1 -> 9 -> 9 -> NULL
2 -> 0 -> 4 -> NULL

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程