Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Adel-Nasim / Data-Structures Public

Code Issues 1 Pull requests 1 Actions Projects Wiki Security Ins

master

Data-Structures / Stack Using Linked List.txt

Adel-Nasim Add files via upload History

1 contributor

82 lines (81 sloc) 1.35 KB

1 #include<iostream>
2 using namespace std;
3 template<class t>
4 class Stack {
5 private:
6 struct StackNode
7 {
8 t item;
9 StackNode*next;
10 };
11 StackNode *topPtr, *curPtr;
12 public:
13 Stack() {
14 topPtr = NULL;
15 }
16 bool isEmpty()
17 {
18 return topPtr == NULL;
19 }
20 void push(t newItem)
21 {
22 StackNode *newPtr = new StackNode;
23 if (newPtr == NULL)
24 cout << "Stack push cannot allocate memory";
25 else
26 {
27 newPtr->item = newItem;
28 newPtr->next = topPtr;
29 topPtr = newPtr;
30 }
31 }
32 void pop() {
33 if (isEmpty())
34 cout << "Stack empty on pop";
35 else {
36 StackNode *temp = topPtr;
37 topPtr = topPtr->next;
38 temp->next = NULL;
39 delete temp;
40 }
41 }
42 void pop(t stackTop)
43 {
44 if (isEmpty())
45 cout << "Stack empty on pop";
46 else {
47 stackTop = topPtr->item;
48 StackNode *temp = topPtr;
49 topPtr = topPtr->next;
50 temp->next = NULL;
51 delete temp;
52 }
53 }
54 void getTop(t stackTop)
55 {
56 if (isEmpty())
57 cout << "stack empty on getTop";
58 else
59 stackTop = topPtr->item;
60 cout << "\nTop Element of the stack is " << stackTop;
61 cout << endl;
62 }
63 void display()
64 {
65 curPtr = topPtr;
66 cout << "\nItems in the stack : ";
67 cout << "[ ";
68 while (curPtr != NULL)
69 {
70 cout <<curPtr->item;
71 curPtr = curPtr->next;
72 }
73 cout << " ]\n";
74 }
75 };
76 int main()
77 {
78 Stack<int>s;
79 s.push(10);
80 s.display();
81 }
82

You might also like