linked list-deletion at end

closed account (1vf9z8AR)
i wrote simple program on linked list to enter values at end and delete values at end.The inserttion is perfect but the deletion is not working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  #include<iostream>
using namespace std;
struct node
{
        int info;
        node *next;
};
node *head=NULL;
void insertend(int x)
{
        node *last=new node;
        last->info=x;
        last->next=NULL;
        if(head==NULL)
                head=last;
        else
        {
                node *temp=head;
                while(temp->next!=NULL)
                        temp=temp->next;
                temp->next=last;
        }
}
void display()
{
        node *np=head;
        while(np!=NULL)
        {
                cout<<np->info<<endl;
                np=np->next;
        }
}
void deleteend()
{
        node *temp=head;
        while(temp->next!=NULL)
                temp=temp->next;
        delete temp;
}
int main()
{
        int data;
        char ch;
        do
        {
                cout<<"Enter value:";cin>>data;
                cout<<endl;
                insertend(data);
                cout<<"Enter more values?(y/n):";cin>>ch;
                cout<<endl;
        }while(ch=='y');
        cout<<"Your list is"<<endl;
        display();
        do
        {
                cout<<"Delete value from end?(y/n):";cin>>ch;
                cout<<endl;
                if(ch=='y')
                        deleteend();
        }while(ch=='y');
         cout<<"Your list is"<<endl;
        display();
        return 0;
}
You need to unlink the found entry from the list. So before you set the next element (line 37) you need to save the current. After the loop is done you need to set next of the saved entry to null[ptr].
closed account (1vf9z8AR)
but next of saved entry is already null
No:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void deleteend()
{
        node *temp=head;
        node *saved=NULL;
        while(temp->next!=NULL) // This will crash if head==NULL
        {
                saved=temp;
                temp=temp->next;
        }
        if(saved) // if saved exists: saved->next != NULL due to while(temp->next!=NULL)
                saved->next=NULL;
        else // if saved is actually NULL it is head
                head=NULL;
        delete temp;
}
Yes, but when you delete the last entry, the entry before last becomes the new last. Therefore you must change the entry before last's next pointer to null to indicate there are now no more nodes in the list.

You have another problem in deleteend(). What happens if head is null (the list is empty)? Hint: The use of temp->next is not valid.


Topic archived. No new replies allowed.