-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackImplUsingLinkedList.java
More file actions
90 lines (73 loc) · 1.97 KB
/
StackImplUsingLinkedList.java
File metadata and controls
90 lines (73 loc) · 1.97 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
83
84
85
86
87
88
89
90
public class StackImplUsingLinkedList<E> implements StackInterface<E>
{
/*
* Stack is implemented using Singly Linked List.
*/
private LinkEntry<E> head;
private int num_elements;
public StackImplUsingLinkedList()
{
head = null;
num_elements = 0;
}
public void push(E e)
{
LinkEntry<E> temp = new LinkEntry<E>();
temp.element = e;
temp.next=head;
head=temp;
num_elements++;
System.out.println("Element is pushed to Stack List is: "+e);
}
public E pop()
{
if (head == null){
System.out.println("Stack List is empty");
return null;
}
E temp = head.element;
head = head.next;
num_elements--;
System.out.println("Element is poped out from Stack List is: "+temp);
return temp;
}
public int size()
{
return num_elements;
}
public void display()
{
LinkEntry<E> current = new LinkEntry<E>();
current=head;
while(current!=null){
System.out.println(current.element.toString());
current=current.next;
}
}
/* ------------------------------------------------------------------- */
/* Inner classes */
protected class LinkEntry<E>
{
protected E element;
protected LinkEntry<E> next;
protected LinkEntry() { element = null; next = null; }
}
public static void main(String[] args){
StackImplUsingLinkedList<Integer> stackList = new StackImplUsingLinkedList<>();
stackList.pop();
stackList.push(1);
stackList.push(2);
stackList.push(3);
stackList.push(4);
System.out.println("Size of list is: "+stackList.size());
stackList.display();
stackList.pop();
System.out.println("Size of list is: "+stackList.size());
stackList.display();
stackList.push(5);
stackList.push(6);
stackList.push(7);
System.out.println("Size of list is: "+stackList.size());
stackList.display();
}
}