Create/Delete/Insert – Single Linked List


#include

using namespace std;

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

struct node* createlist()
{
    node *temp, *firstNodePtr, *last;
    int intNumOfNodes=0;
    firstNodePtr = (node*)malloc(sizeof(node));
    temp=firstNodePtr;
    cout<<"Enter the number of nodes you want in the list: ";
    cin>>intNumOfNodes;
    if(intNumOfNodes!=0)
    {
        while(intNumOfNodes!=0)
        {
            temp->next = (node*)malloc(sizeof(node));
            cin>>temp->data;
            last=temp;
            temp=temp->next;
            intNumOfNodes–;
        }
        last->next=NULL;
        delete(temp);       
    }
    else
    {
        firstNodePtr = NULL;
    }
    return(firstNodePtr);
}

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

void deleteHeader(struct node **ptrHeader)
{
    node *current,*temp;
    current=*ptrHeader;
    temp=current->next;
    *ptrHeader = temp;
    current=NULL;
    display(*ptrHeader);           
}

void deleteTail(struct node **ptrHeader)
{
    node *last, *temp;
    temp=*ptrHeader;
    while(temp->next)
    {
        last=temp;
        temp=temp->next;
    }
    last->next=NULL;
    temp=NULL;
    display(*ptrHeader);   
}

void deleteANode(struct node **header, char choice)
{
    if(choice == ‘h’)
    {
        cout<<"You have chosen to delete the header node!!!"<<endl;
        deleteHeader(header);
    }
    else if(choice == ‘l’)
    {
        cout<<"You have chosen to delete the last node!!!"<<endl;
        deleteTail(header);
    }
    else
    {
        node *temp, *last;
        int counter=0, intPos=0;
        temp=*header;
        cout<<"Enter the position of the node that you want to delete."<<endl;
        cin>>intPos;
        while(counter!=intPos)
        {
            last=temp;
            temp=temp->next;
            counter++;
        }   
        last->next = temp->next;
        delete(temp);
        display(*header);       
    }
}

void main()
{
    node *headerPtr;
    node **ptrHeaderPtr;
    char choice;
    headerPtr = createlist();
    if(headerPtr)
    {
        ptrHeaderPtr = &headerPtr;
        display(headerPtr);
        cout<<"Which node do you want to delete? (h/p/l): ";
        cin>>choice;
        deleteANode(ptrHeaderPtr, choice);
        //display(headerPtr);
    }
    else {cout<<"You enterd a 0 value for list size. Exiting…";}
}

Advertisements

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s