-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStack with LinkedList implementation.cs
147 lines (125 loc) · 3.11 KB
/
Stack with LinkedList implementation.cs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
// create Object of Implementing class
StackUsingLinkedlist stk = new StackUsingLinkedlist();
// insert Stack value
stk.push(11);
stk.push(22);
stk.push(33);
stk.push(44);
// print Stack elements
stk.display();
// print Top element of Stack
Console.Write("\nTop element is {0}\n", stk.peek());
// Delete top element of Stack
stk.pop();
stk.pop();
// print Stack elements
stk.display();
// print Top element of Stack
Console.Write("\nTop element is {0}\n", stk.peek());
}
}
public class StackUsingLinkedlist
{
// A linked list node
private class Node
{
// integer data
public int data;
// reference variable Node type
public Node Next;
public Node(int data)
{
this.data = data;
this.Next = null;
}
}
// create global top reference variable
Node top;
// Constructor
public StackUsingLinkedlist()
{
this.top = null;
}
// Utility function to add
// an element x in the stack
// insert at the beginning
public void push(int x)
{
// create new node temp and allocate memory
Node newNode = new Node(x);
// check if stack (heap) is full.
// Then inserting an element
// would lead to stack overflow
if (newNode == null)
{
Console.Write("\nHeap Overflow");
return;
}
// put top reference into temp link
newNode.Next = top;
// update top reference
top = newNode;
}
// Utility function to check if
// the stack is empty or not
public bool isEmpty()
{
return top == null;
}
// Utility function to return
// top element in a stack
public int peek()
{
// check for empty stack
if (!isEmpty())
{
return top.data;
}
else
{
Console.WriteLine("Stack is empty");
return -1;
}
}
// Utility function to pop top element from the stack
public void pop() // remove at the beginning
{
// check for stack underflow
if (top == null)
{
Console.Write("\nStack Underflow");
return;
}
// update the top pointer to
// point to the next node
top = (top).Next;
}
public void display()
{
// check for stack underflow
if (top == null)
{
Console.Write("\nStack Underflow");
return;
}
else
{
Node temp = top;
while (temp != null)
{
// print node data
Console.Write("{0}->", temp.data);
// assign temp link to temp
temp = temp.Next;
}
}
}
}