linked list problem

I have a problem in my simple linked list program


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
#include "stdafx.h"
#include<iostream>
using namespace std;
struct link
  {
	int data;
	link *next;
  };

class linklist
  {
private:
	  link *first;
public:
	  linklist()
	    {
			first=NULL;
	    }
void add(int d);
void show();
};
void linklist::add(int d)
	{
		link* newlink=new link;
		newlink->data=d;
		newlink->next=first;
		first=new link;
	}
void linklist::show()
	{
         link *current=first;
	    while(current!=NULL)
		{
		     cout<<current->data<<endl;
		     current=current->next;
	         }

	}
int main()
{
	linklist l;
	l.add(1);
	l.add(2);
	l.add(3);
	l.add(4);
	l.add(5);
	l.show();
	return 0;
}



my program output incorrect , please help me..
The problem is in your add function. Your first is realy your last link. Every time you add something, a new first is created ,so its next doesn't point anywhere and you cannot trace back your list. What you need to do is first->next = newlink; instead. Then set newlink->next to 0. Otherwise your show() loop will never terminate.
Hope this helps
comments included
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

void linklist::add(int d)
	{
		link* newlink=new link;
		newlink->data=d;
		newlink->next=NULL;// now we created a new one we need to attach it
		
		if(first==NULL) // for the very first time
		{
          first=newlink;       
        }else
        {// when it comes here  we have few links in the list
        // there are two options we can add the newlink at the begining
        // or at the end of the list
        // add newlink at begining so the last one will be the head
        newlink->next=first; // keep the avaialable list as next
        first=newlink; // make the first point to the newly created
        
        /*
        // add at the end, first will be the head always
        // iterate through the first find out the last one 
        link* temp=first;
        while(temp->next != NULL)
        {
           temp=temp->next;
        }
        // we are in the last one
        temp->next=newlink;
        
               
        
        */             
	
	}
}
Last edited on
Topic archived. No new replies allowed.