forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_2.cpp
More file actions
78 lines (63 loc) · 1.41 KB
/
Exercise_2.cpp
File metadata and controls
78 lines (63 loc) · 1.41 KB
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
/* Implement Stack using Linked List */
#include <iostream>
using namespace std;
// A structure to represent a stack
class StackNode {
public:
int data;
StackNode* next;
};
StackNode* newNode(int data)
{
StackNode* stackNode = new StackNode();
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}
int isEmpty(StackNode* root)
{
//Your code here
return !root;
}
void push(StackNode** root, int data)
{
//Your code here
StackNode* stackNode = newNode (data);
stackNode->next = *root;
*root = stackNode;
cout << data << "Pushed to stack " << endl;
}
int pop(StackNode** root)
{
//Your code here
if (isEmpty(*root))
return 0;
StackNode* temp = *root;
*root = (*root)->next;
int poppedData = temp->data;
free(temp);
}
int peek(StackNode* root)
{
//Your code here
if (isEmpty (root))
return 0;
return root->data;
}
int main()
{
StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
cout << pop(&root) << " popped from stack\n";
cout << "Top element is " << peek(root) << endl;
return 0;
}
/*
Time Complexities of Stack implementation using Linked List
Push() - O(1)
pop() - O(1)
isEmpty() - O(1)
peek() - O(1)
*/