0% found this document useful (0 votes)
4 views4 pages

Assignment

The document contains C++ code that defines a linked list and implements functions to remove leading zeroes, reverse the list, and add two linked lists representing numbers. It includes a main function that creates two linked lists, adds them, and prints the result. The code effectively handles the addition of numbers represented in reverse order in linked lists.

Uploaded by

yashfreefire83
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

Assignment

The document contains C++ code that defines a linked list and implements functions to remove leading zeroes, reverse the list, and add two linked lists representing numbers. It includes a main function that creates two linked lists, adds them, and prints the result. The code effectively handles the addition of numbers represented in reverse order in linked lists.

Uploaded by

yashfreefire83
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

class Node {
public:
int data;
Node *next;
Node(int data) {
this-> data = data;
this-> next = NULL;
}
};

Node *RemovingZeroes(Node* head) {


while(head->next != NULL && head->data == 0)
head = head->next;
return head;
}
Node *reverse(Node *head) {
Node *prev = NULL;
Node *curr = head;
Node *next = NULL;

while (curr != NULL) {


next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
Node *AddingLinkedlist(Node *num1, Node *num2) {
Node *prev = NULL;
Node *curr = NULL;
int carry = 0;

num1 = RemovingZeroes(num1);
num2 = RemovingZeroes(num2);

num1 = reverse(num1);
num2 = reverse(num2);

while (num1 != NULL || num2 != NULL || carry != 0) {


int sum = carry;

if (num1 != NULL) {
sum = sum+ num1->data;
num1 = num1->next;
}

if (num2 != NULL) {
sum = sum + num2->data;
num2 = num2->next;
}

Node* newnode = new Node(sum % 10);

carry = sum / 10;

if(prev == NULL) {
prev = newnode;
curr = newnode;
}
else {
curr->next = newnode;
curr = curr->next;
}
}

return reverse(prev);
}

void printing(Node *head) {


Node *temp = head;
while (temp != NULL) {
cout << temp->data;
if(temp->next != NULL){
cout << " -> ";
}
temp = temp->next;
}
}

int main() {

Node *num1 = new Node(1);


num1->next = new Node(2);
num1->next->next = new Node(3);

Node *num2 = new Node(9);


num2->next = new Node(9);
num2->next->next = new Node(9);

Node *sum = AddingLinkedlist(num1, num2);


printing(sum);

return 0;
}

You might also like