public class Stack implements Cloneable {
Node top; // pointing to the toppest node on a stack
Node pop() {
if (top != null) {
Node item = top;
top = top.next;
return item;
}
return null;
}
void push(int k) {
Node t = new Node(k);
t.next = top;
top = t;
}
Object peek() {
return top.data;
}
public Stack clone() throws CloneNotSupportedException {
return (Stack) super.clone();
}
boolean isEmpty(){
return (this.top ==null);
}
}
public class Queue {
// in this implementation, tail.next is always null;, so that we can enqueue() at tail
// thus, delete at head();
Node head, tail;
void enqueue(Node item){// enqueue at tail.
if(tail ==null){
tail = item;
head = item;
}else{
tail.next = item;
item.next = null;
tail = item;
}
}
Object dequeue(){// dequeue at head
// head point to the just added item. or the first in a single list
if(head!=null){
Object item = head;
head = head.next;
return item;
}
return null;
}
}
Learned:
1: Constructor call must be the first statement in a constructor
No comments:
Post a Comment