Stack Implementation of Linked Lists

Hey guys,

C++ newbie here, I've been trying to make my own stack class that utilizes a linked list.

The expected result of my program was that once I made an object from my own class, called its 'push' function to add a number, then print out the 'top', it would display the number.

For my push function, I was aiming to make it so that it would check if it was empty or not. If it was empty, I'd make the 'next' pointer of the new node point to null, then assign the head pointer to point to the new node.

If it wasn't, it would store the address of 'head' in a temporary pointer, then assign head to the newly added node. Then lastly it would assign the 'next' pointer of the head/top node to temp in order to establish a link for the previous node.

Instead it prints "List is empty" and below it a very long number e.g. "1453579136".

I'm assuming the problem lies in my push function however I'm fairly new to pointers and have been unable to fix this issue.

Can anyone explain the reason behind this result? Any constructive comments on how to improve my code are also welcome.

Thanks :)

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

#include <iostream>

class sList
{
public:
	sList() {
		temp = NULL;
	
		head = NULL;

	}

	bool isEmpty()
	{
		if (head == NULL) return true;
	}

	void push(int _data)
	{
		node* n = new node;
		n->data = _data;
		if (isEmpty())
		{
			n->next = NULL;
			head = n;
		}

		else
		{
			temp = head;
			head = n;
			head->next = temp;
		}
	}
	void pop()
	{
		if (isEmpty()) std::cout << "List is empty!\n";

		else
		{
			temp = head;
			head = head->next;
			delete (temp);
		}
	}
	int top()
	{
		if (isEmpty()) std::cout << "List is empty\n";

		else return head->data;

	}

	

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

	node* temp;
	
	node* head;


};

int main()
{
	

	sList test;
	
	test.push(1);

	std::cout << test.top();
    return 0;
}
constructive comments ... also welcome


- indent your code properly (search Allman style)
- you don't need temp as a data member since it's a singly linked list, any temp node you declare with new can handle the switches
- line 45 - delete not required since temp not created with new operator ... on that look up smart pointers
- on the other hand, n (line 22) needs to be deleted
- line 23 - not strictly disallowed but avoid variable names with prefix underscore
(http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)

1
2
3
4
5
else
{
	n->next = head;
	head = n;
}



Topic archived. No new replies allowed.