Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- class node{
- protected:
- int element;
- node* link;
- public:
- //constructor that accepts only element
- node(int element) {
- this->element = element;
- this->link = NULL;
- }
- //constructor that accepts both link and element
- node(int element, node* link){
- this->element = element;
- this->link = link;
- }
- //method to update the element
- void updateData(int element){
- this->element = element;
- }
- //method to update or setup link
- void updateLink(node* link){
- this->link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this->element;
- }
- //method to get the next node
- node* getNextNode(){
- return this->link;
- }
- };
- class Linkedlist {
- public:
- node *head;
- //constructor for the Linked List class
- Linkedlist() {
- head = NULL;
- }
- //returns head node
- node *getHead() {
- return this->head;
- }
- // method to add a node at the end
- void insert(int element) {
- node *tempNode = new node(element);
- node *p = head;
- if (head == NULL) {
- head = tempNode;
- return;
- }
- else {
- while (p->getNextNode() != NULL) {
- p = p->getNextNode();
- }
- p->updateLink(tempNode);
- return;
- }
- }
- //method to display all the elements of the Linked List
- void display() {
- cout << "\n";
- node *tempNode = head;
- while (tempNode != NULL) {
- if (tempNode->getNextNode() != NULL)
- cout << tempNode->getElement() << " --> ";
- else
- cout << tempNode->getElement();
- tempNode = tempNode->getNextNode();
- }
- return;
- }
- void addOne(){
- this->reverse(this->head);
- addingOneUtil();
- this->reverse(this->head);
- }
- private:
- // adding one to linked list
- void addingOneUtil(){
- int carry = 1;
- int sum = 0;
- node* start = this->head;
- while(start != NULL && carry != 0){
- sum = start->getElement() + carry;
- start->updateData(sum % 10);
- carry = sum / 10;
- start = start->getNextNode();
- }
- if(carry != 0){
- this->insert(carry);
- }
- }
- // function to reverse linked list
- void reverse(node* head){
- if(head == NULL){
- return;
- }
- node* next = NULL;
- node* prev = NULL;
- node* current = head;
- while(current != NULL){
- next = current->getNextNode();
- current->updateLink(prev);
- prev = current;
- current = next;
- }
- this->head = prev;
- }
- };
- int main() {
- cout<<"Program to add one to a number represented by Linked List";
- Linkedlist l1;
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.insert(9);
- l1.display();
- cout<<"\nNumber after adding one is : ";
- l1.addOne();
- l1.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment