Link List Problem

This Code is Working Fine but i want the output in right order not in reverse order i am so confused (new to data structure)


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
#include<iostream>
using namespace std;

class Node
{
private:
	Node* start;
	Node* next;
	Node* temp;
	int data;
public:
	void insert(int);
	void display();
	Node();
};

Node::Node()
{
	start = NULL;
}

void Node::insert(int item)
{
	temp = new Node;
	temp->data = item;
	temp->next = start;
	start = temp;
}

void Node::display()
{
	Node* show = temp;
	while (show != NULL)
	{
		cout << show->data << endl;
		show = show->next;
	}
}


int main()
{
	Node n;
	n.insert(1);
	n.insert(2);
	n.insert(3);
	n.insert(4);
	n.insert(5);

	n.display();
	system("pause");

}




Expected Output
1
2
3
4
5




Getting Output
5
4
3
2
1
Last edited on
Normally a list uses two classes: one for the list itself and one for a node within the list. You're using one class to represent both, which is a little unusual.

temp should be a local variable declared whereever you need it, not a member of the Node class.

Node's constructor should set the next pointer to NULL. Otherwise the last item's next pointer will point off to lala land.

That said, your items are printing in reverse order because you insert the items at the beginning of the list, so they occur in the list in the reverse order from which they were inserted.
- use the ctor's to initialize objects when feasible;
- const qualify variables and member methods likewise;
- the linked list also needs a destructor
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<iostream>
using namespace std;

struct Node
{
	Node* next;
	int data;
	Node(const int d) : data(d), next(nullptr) {}
	~Node() {std::cout << "Goodbye " << data << '\n';}
};
struct LList
{
    Node* start = nullptr;
    void insert (const int& item);
    void display()const;
    ~LList()
	{
	    Node* temp = start;
	    while (temp)
        {
            Node* next = temp -> next;
            delete temp;
            temp = next;
        }
        start = nullptr;
    }
};
void LList::insert(const int& item)
{
	Node* temp = new Node(item);
	if(!start)
    {
        start = temp;
    }
    else
    {
        Node* last = start;
        while (last -> next)
        {
            last = last -> next;
        }
        last -> next = temp;
    }
}
void LList::display()const
{
	Node* show = start;
	while (show)
	{
		std:: cout << show ->data << '\n';
		show = show->next;
	}
}
int main()
{
	LList n;
	n.insert(1);
	n.insert(2);
	n.insert(3);
	n.insert(4);
	n.insert(5);

	n.display();
}

Output
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
Goodbye 1
Goodbye 2
Goodbye 3
Goodbye 4
Goodbye 5


Topic archived. No new replies allowed.