Solved programming problem

Insert and Display in Doubly Linked List with C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list  *next,*prev;

};

typedef struct list node;

node *start=NULL;

void insert_node()

{

    node *temp,*last,*back;

    temp = new node();

    cout<<"Insert Data: ";

    cin>>temp->data;

    temp->next = NULL;

    temp->prev = NULL;

    back = temp;

    if(start==NULL) ///if it is the first node

    {

        start= new node();

        start->data= temp->data;

        start->next=NULL;

        start->prev=NULL; ///only for the 1st node prev = NULL;

        back = start;

    }

    else

    {

        last =start;

        while(last->next!= NULL)

        {

            last = last->next;

        }

        last->next = temp; ///save data in last node

        last->prev = back; ///point the previous node

        back = temp; ///save temp as last back node;

    }

}

void display() ///print the function

{

    node *temp = start;

    cout<<"Linked List: "<<endl;

    while(temp!= NULL)

    {

        cout<<temp->data<< " ";

        temp = temp -> next;

    }

    cout<<endl;

}

int main()

{

    int flag=1;

    while(flag==1)

    {

        cout<<"Press 1 to Enter Node: ";

        cin>>flag;

        if(flag!=1)break;

        insert_node();

    }

    display(); ///print function

    return 0;

}

Output

Press 1 to Enter Node: 1
Insert Data: 5
Press 1 to Enter Node: 1
Insert Data: 7
Press 1 to Enter Node: 1
Insert Data: 8
Press 1 to Enter Node: 0
Linked List:
5 7 8

Join the discussion

Add your comment