linked list

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>

using namespace std;

struct node{
	int data;
	node *next;
	node *prev;
}*head,*tail;

void addNodeFront( int data ){

	node *curr;
	if( head == NULL ){
		curr = new node;
		head = curr;
		tail = curr;
		curr->next = NULL;
		curr->prev = NULL;
		curr->data = data;
	}
	if( head != NULL ){
		curr = new node;
		curr->next = NULL;
		tail->next = curr;
		curr->prev = tail;
		tail = curr;
		curr->data = data;
	}
}

void displayForward(){

	node *temp1;
	temp1 = head;

	int c = 1 ;

	if( temp1 == NULL ){
		cout << "No data inside ! " << endl;
	}
	while( temp1 != NULL ){
		cout << "Node " << c << " : " << temp1->data << endl;
		temp1 = temp1->next;
		c++;
	}
}

void displayReverse(){
	if( head == NULL ){
		cout << "No data inside ! " << endl;
	}

	node *prev = NULL , *current = NULL , *next = NULL;
	current = head;
	while( current != NULL ){
		next = current->next;
		current->next = prev;
		prev = current;
		current = next;
	}
	head = prev;

	while( tail != NULL ){
		cout << tail->data << endl;
		tail = tail->next;
	}

}

int main(){

	addNodeFront ( 45 );
	addNodeFront ( 50 );
	addNodeFront ( 55 );
	addNodeFront ( 60 );
	addNodeFront ( 70 );

	displayForward();
	displayReverse();

	system( "pause" );
	return 0;
}


i just push 1 for 45
but why my program will show that i push 2 value 45?
Might try an else on line 22.
it fixed ! mind tell me why?
If the condition in line 14 evaluates to true, then lines 15 through 20 are executed, which inserts the data into the list and coincidentally sets head to a non-null value.

This being the case, when line 22 is encountered, the condition in the if there will also evaluate to true, and lines 23 through 28 will be executed, inserting the data into the list again.
Topic archived. No new replies allowed.