-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStackLinked.java
More file actions
70 lines (66 loc) · 1.74 KB
/
MyStackLinked.java
File metadata and controls
70 lines (66 loc) · 1.74 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
/***
MyStackLinked - linked implementation of the MyStack interface
**/
public class MyStackLinked implements MyStack{
//define the data container
private Node top;
//utility variables
private int count;
private int MAX=10;
//no constructor is required to be explicity defined
//sentinel methods
public boolean isFull() { return false; }
public boolean isEmpty() { return top==null; }
//the standard method names
public boolean push(Object item){
boolean ok=!isFull();
Node node=new Node(item);
/*if(isEmpty()){
top=node;
}
else{
node.setNext(top);
top=node;
}*/
if(!isEmpty()){
node.setNext(top);
}
top=node;
count++;
return ok;
}
public Object pop(){
Object item=peek();
if(item!=null){
Node temp=top;
top=temp.getNext();
temp=null;
count--;
}
return item;
}
public Object peek(){
/*Object obj=null
if(!isEmpty()){
obj=top.getItem();
}
return obj;*/
//use ternary operator
return (!isEmpty())?top.getItem():null;
}
public String toString(){
//REMEMBER: Stack is LIFO (Last-In, First-Out)
StringBuffer sb=new StringBuffer();
/*
Node temp=top;
while(temp!=null){
sb.append(top.getItem());
temp=temp.getNext();
}*/
/*for(Node temp=top;temp!=null;temp=temp.getNext()){
sb.append(temp.getItem());
}*/
for(Node temp=top;temp!=null;sb.append(temp.getItem()),temp=temp.getNext());
return sb.toString();
}
}//end of class