infinite loop for pointer variable in link list

I am getting and infinite loop for loop pointer variable current which points to head and is incremented by current->next in while loop. I use the pointer variable the same way in my display routine and it works. Here is listing of code.


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
#include "stdafx.h"
#include<iostream>

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

void initNode(struct node *head,int nodeData)
{
		head->data = nodeData;
		head->next = NULL;
}

void addNode(struct node *head,int newdata)
	{
	 node *current = head; 
		
	while(current)
	 {
         if (current->next == NULL)
		 {
          node *newNode = new node;
		  current->next = newNode;
		  newNode->data = newdata;
		  newNode->next = NULL;
		 }
		 current = current->next;
         }
      
	}

void display(struct node *head)
	{
		using namespace std;
		node *cur = head;
		while(cur)
		{
          cout<<"data = "<< cur->data<< endl;
		  cur = cur->next;
		}
	} 

int main()
{
	using namespace std;

    node *head = new node;

	initNode(head,10);
	display(head);
        addNode(head,20);
	display(head);
	addNode(head,30);
	display(head);


	cin.clear();
	cin.ignore(255,'/n');
	cin.get();

	return 0;
}
Your addNode function has an infinite loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
while(current)
	 {
         if (current->next == NULL)
		 {
          node *newNode = new node;
		  current->next = newNode;
		  newNode->data = newdata;
		  newNode->next = NULL;
		 }
		 current = current->next; // current now points to new node.
         }
      
	}


In this loop current shall never be NULL because you always assign it to point to new Node. instead, you should just break out of the loop after adding.

Or I would do it as follows:

1
2
3
4
5
6
7
8
9
while (current->next) // move to the last node
   current = current->next;

// Now simply add the new node.
node *newNode = new node;
current->next = newNode;
newNode->data = newdata;
newNode->next = NULL;
current = current->next;
Last edited on
Topic archived. No new replies allowed.