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
82 lines (71 loc) · 1.75 KB
/
Exercise_2.cpp
File metadata and controls
82 lines (71 loc) · 1.75 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
79
80
81
82
// Time Complexity:
// push() -> O(1)
// pop() -> O(1)
// peek() -> O(1)
// isEmpty() -> O(1)
//
// Space Complexity:
// O(n) — where n is the number of elements pushed onto the stack,
// because each push creates a new node in the linked list.
//
// Did this code successfully run on Leetcode?
// This was not a LeetCode problem, but the code runs successfully on terminal.
//
// Any problems faced while coding this:
// Understanding pointer manipulation and using StackNode** for push/pop.
#include <bits/stdc++.h>
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)
{
return !root; //Your code here
}
void push(StackNode** root, int data)
{
StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
//Your code here
}
int pop(StackNode** root)
{
if (isEmpty(*root)){
cout << "Stack Underflow\n";
return INT_MIN;
}
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp -> data;
delete temp;
return popped;//Your code here
}
int peek(StackNode* root)
{
if (isEmpty(root)){
cout << "Stack is empty\n";
return INT_MIN;//Your code here
}
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;
}