Question

In: Computer Science

I am trying to add two linked-list based integers, but the program keeps giving me the...

I am trying to add two linked-list based integers, but the program keeps giving me the incorrect result. I am trying to add (List 1: 43135) + (List 2: 172). I have pasted the code below

#include <iostream>
using namespace std;

//Linked list node
class Node
{
   public:
   int num;
   Node* next;
};

//Function to create a new node with given numbers
Node *new_Node(int num)
{
   Node *newNode = new Node();
   newNode->num = num;
   newNode->next = NULL;
   return newNode;
}

//Function to insert a node at the beginning of the Linked List
void push(Node** head, int newNum)
{
   Node* newNode = new_Node(newNum);

   newNode->next = (*head);

   (*head) = newNode;
}

// Function to add two linked lists and return the head node of the list
Node* addTwoLists (Node* first, Node* second)
{
   Node* result = NULL;
   Node *temp, *prev = NULL;
   int carry = 0, sum;

//the while loop will perform various calculations on the linked-list
// the loop will execute while both lists exist
   while (first != NULL || second != NULL)
   {
       sum = carry + (first? first->num: 0) +(second? second->num: 0);

       carry = (sum >= 10)? 1 : 0;

       sum = sum % 10;

       temp = new_Node(sum);

       if(result == NULL)
           result = temp;

       else
           prev->next = temp;
           prev = temp;

       if (first) first = first->next;
       if (second) second = second->next;
   }

   if (carry > 0)
   temp->next = new_Node(carry);
   return result;
} //end of while loop

//Function to print the linked list
void printList(Node *node)
{
   while(node != NULL)
   {
       cout << node->num << " ";
       node = node->next;
   }
   cout<<endl;
}

//main function
int main()
{
   Node* result = NULL;
   Node* first = NULL;
   Node* second = NULL;

   // create first list
push(&first, 5);
   push(&first, 3);
   push(&first, 1);
   push(&first, 3);
   push(&first, 4);
   cout <<"First List is ";
   printList(first);

   // create second list
   push(&second, 2);
   push(&second, 7);
   push(&second, 1);
   cout<<"Second List is ";
   printList(second);

   //results of the two lists after it has been added
   result = addTwoLists(first, second);
   cout<<"The sum of the two linked-lists is ";
   printList(result);

return 0;
}

Solutions

Expert Solution

#include <iostream>
using namespace std;

//Linked list node
class Node
{
public:
int num;
Node* next;
};

//Function to create a new node with given numbers
Node *new_Node(int num)
{
Node *newNode = new Node();
newNode->num = num;
newNode->next = NULL;
return newNode;
}

//Function to insert a node at the beginning of the Linked List
void push(Node** head, int newNum)
{
Node* newNode = new_Node(newNum);

newNode->next = (*head);

(*head) = newNode;
}

// Function to add two linked lists and return the head node of the list
Node* addTwoLists (Node* first, Node* second)
{
   //the problem with this code is logic, two add integers, you have to add from the end
   //but you are adding from begining, otherwise everything is fine
   //one way to simply, is, add integers in linked list in reverse order
   //so, that your code will work correctly
   //i, have modified, so that it work as desired
Node* result = NULL;
Node *temp, *prev = NULL;
int carry = 0, sum;

//the while loop will perform various calculations on the linked-list
// the loop will execute while both lists exist
while (first != NULL || second != NULL)
{
sum = carry + (first? first->num: 0) +(second? second->num: 0);

carry = (sum >= 10)? 1 : 0;

sum = sum % 10;

temp = new_Node(sum);

if(result == NULL)
result =prev= temp;//modified here

else
prev->next = temp;
prev = temp;

if (first) first = first->next;
if (second) second = second->next;
}

if (carry > 0)
temp->next = new_Node(carry);
return result;
} //end of while loop

//Function to print the linked list
void printList(Node *node)//modified here
{if(node ==NULL)return;
printList( node->next);
cout << node->num << " ";


}

//main function
int main()
{
Node* result = NULL;
Node* first = NULL;
Node* second = NULL;

// create first list
//modified here also
push(&first, 4);
push(&first, 3);
push(&first, 1);
push(&first, 3);
push(&first, 5);
cout <<"First List is ";
printList(first);
   cout<<endl;
// create second list
push(&second, 1);
push(&second, 7);
push(&second, 2);
cout<<"Second List is ";
printList(second);
cout<<endl;
//results of the two lists after it has been added
result = addTwoLists(first, second);
cout<<"The sum of the two linked-lists is ";
printList(result);

return 0;
}

output:

First List is 4 3 1 3 5
Second List is 1 7 2
The sum of the two linked-lists is 4 3 3 0 7

Process exited normally.
Press any key to continue . . .



//PLS give a thumbs up if you find this helpful, it helps me alot, thanks.


Related Solutions

how do you add two matrices linked list in java? (am using linked list because 2D...
how do you add two matrices linked list in java? (am using linked list because 2D arrays are not allowed.) ex [1st matrix] 1 3 2 4 2 1 3 2 4 + [2nd matrix] 3 2 3 2 1 4 5 2 3 = [3rd matrix] 4 5 5 6 3 5 8 4 7
Hi, I would like to test a java program. I am learning linked list and going...
Hi, I would like to test a java program. I am learning linked list and going to make a linked lists for integer nodes. For instance, I am going to add the numbers 12, 13, and 16 to the list and then display the list contents and add 15 to the list again and display the list contents and delete 13 from the list and display the list contents and lastly delete 12 from the list and display the list...
I am writing a program that will work with two other files to add or subtract...
I am writing a program that will work with two other files to add or subtract fractions for as many fractions that user inputs. I need to overload the + and - and << and >> opperators for the assignment. The two files posted cannot be modified. Can someone correct the Fraction.ccp and Frction.h file that I am working on? I'm really close. // // useFraction.cpp // // DO NOT MODIFY THIS FILE // #include "Fraction.h" #include<iostream> using namespace std;...
Hello Everyone, Can anyone tell me why my program will not run? I am trying to...
Hello Everyone, Can anyone tell me why my program will not run? I am trying to work on abstract base classes... not sure what is going on. import math from abc import ABC from abc import abstractmethod #TODO: convert this to an ABC class Shape(ABC): def __init__(self): self.name = "" def display(self): print("{} - {:.2f}".format(self.name, self.get_area())) #TODO: Add an abstractmethod here called get_area @abstractmethod def get_area(self): if self.name == "Circle": get_area()= 3.14 * radius * radius else: get_area() = self.length...
I am trying to write a UDP socket program in which there is a server program...
I am trying to write a UDP socket program in which there is a server program and a client program. This is what I have but I can't figure out where I am going wrong. This is the input and expected output: > gcc udpclient.c –o clientout > gcc udpserver.c –o serverout > ./serverout 52007 ‘to celebrate’ & > ./clientout odin 52007 ‘Today is a good day’ Today is a good day to celebrate //UDP echo client program #include #include...
I am trying to create a makefile for the following program in Unix. The C++ program...
I am trying to create a makefile for the following program in Unix. The C++ program I am trying to run is presented here. I was wondering if you could help me create a makefile for the following C++ file in Unix and show screenshots of the process? I am doing this all in blue on putty and not in Ubuntu, so i don't have the luxury of viewing the files on my computer, or I don't know how to...
Hello! Html question. I am trying to add a background to a page. How would i...
Hello! Html question. I am trying to add a background to a page. How would i do this? I have tried using a jpg. The code is posted below. i used the background-image: url function. Any help of different ways to do this would be appreciated! Thank you! CODE: <!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: block; color: white; text-align:...
Write a program where you- 1. Create a class to implement "Double Linked List" of integers....
Write a program where you- 1. Create a class to implement "Double Linked List" of integers. (10) 2. Create the list and print the list in forward and reverse directions. (10)
I am trying to write a java program that determines if an inputted year is a...
I am trying to write a java program that determines if an inputted year is a leap year or not, but I am not able to use if else statements how would I do it. I don't need the code just advice.
Given a linked list of integers, remove any nodes from the linked list that have values...
Given a linked list of integers, remove any nodes from the linked list that have values that have previously occurred in the linked list. Your function should return a reference to the head of the updated linked list. (In Python)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT