linked list-delete from beginning

In delbeg function why can't we just use start=start->next?

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
#include<iostream>
using namespace std;
struct node
{
        int data;
        node *next;
};
node *start=NULL;
void insertbeg(int);
void delbeg();
void display();
int main()
{
        int x;
        char ch;
        do
        {
                cout<<"Enter value:";cin>>x;
                cout<<endl;
                insertbeg(x);
                cout<<"Do you want to continue?(y/n):";cin>>ch;
                cout<<endl;
        }while(ch=='y');
        cout<<"Your list is"<<endl;
        display();
        do
        {
                cout<<"Do you want to delete the beginning value?(y/n)";cin>>ch;
                cout<<endl;
                if(ch=='y')
                delbeg();
        }while(ch=='y');
          cout<<"Your list is"<<endl;
          display();
          return 0;
}
void insertbeg(int n)
{
        node *temp=new node;
        temp->data=n;
        temp->next=start;
        start=temp;
}
void delbeg()
{
        node *ptr=start;
        start=start->next;
        delete ptr;
}
void display()
{
        node *np=start;
        while(np!=NULL)
        {
                cout<<np->data<<endl;
                np=np->next;
        }
}
you need to delete the record, but not until you've got the "next" pointer from it, so need to keep a pointer to it for that reason. After you've deleted start you cant reference it anymore because its deleted :)

you could have just as easily said;
1
2
3
node *newStart= start->next;
delete start;
start = newStart;
I'm not sure what you're asking.

Are you asking if you can do this:
1
2
3
4
void delbeg()
{   delete start;     // memory occupied by node pointed to by start returned to heap.
    start=start->next;  // Not valid. What start points to is no longer valid.
}

As the comment indicates, after line 2 executes, what start points to no longer exists. Therefore the use of start->next on line 3 is invalid.

Last edited on
oooooooooooooh @Jaybob66 your answer made it so much clearer
Registered users can post here. Sign in or register to post.