Linked list problems


/*
You have two “set” of numbers represented by “two” linked lists, where each node contains a single digit.
Write a function that adds the two numbers “in the corresponding nodes” and returns the sum as a “third” linked list

*/

#include
using namespace std;

struct node{int data;struct node *next;};

void display(struct node *header)
{
    cout<<endl;
    node *ptr;
    ptr=header;
    cout<<"The list is:    ";
    while(ptr!=NULL)
    {
        cout<data<<"    ";
        ptr=ptr->next;
    }
}

struct node* createlist()
{
    int counter=0;
    node *first, *last, *temp;
    first= (node*)malloc(sizeof(node));
    temp=first;

    cout<<"Enter the number of elements:    ";
    cin>>counter;
    while(counter!=0)
    {
        temp->next=(node*)malloc(sizeof(node));
        cout<<"The node data is:    ";
        cin>>temp->data;
        last=temp;
        temp=temp->next;       
        counter–;
    }
        last->next=NULL;
        return first;
}

struct node* createlist(node *pointer3,int nodevalue)
{
    node *ptr;
    ptr=pointer3;
    if(ptr==NULL)
    {
        node *temp;
        temp=(node*)malloc(sizeof(node));
        temp->data=nodevalue;
        return temp;
    }
    else
    {
        node *last;
        last=pointer3;
        pointer3->next=(node*)malloc(sizeof(node));
        pointer3=pointer3->next;
        pointer3->data=nodevalue;
        return pointer3;
    }   
}

struct node* addlinkedlist(struct node *header1, struct node *header2)
{
    cout<<endl;
    node *firstlist,*secondlist, *pointer3, *baseptr;

    firstlist=header1;
    secondlist=header2;
    pointer3 = NULL;   

    while(firstlist !=NULL && secondlist !=NULL)
    {

        if(pointer3==NULL)
        {
            baseptr = createlist(pointer3,firstlist->data    + secondlist->data);
            pointer3=baseptr;
        }
        else   
        {
            pointer3 = createlist(pointer3,firstlist->data    + secondlist->data);           
        }

        secondlist=secondlist->next;
        firstlist= firstlist->next;
    }
    return baseptr;
}

void main()
{
    cout<<"You have two set of numbers represented by two linked lists, where each node contains a single digit.";
    cout<<"Write a function that adds the two numbers in the corresponding nodes and returns the sum as a third linked list";
    node *header1, *header2, *header3;
    header1 = createlist();
    header2=createlist();
    display(header1);
    display(header2);
    header3= addlinkedlist(header1, header2);
    display(header3);   
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s