Escolar Documentos
Profissional Documentos
Cultura Documentos
• Test (Reminder):
• There will be a 90 minute test
• Friday 15th at 3-5pm
• EA006
COMP103 – 2006/T3 2
A Linked Stack I
• Implement a Stack using a linked list.
J
P C
X
• pop()
TOP
A H
• push(“A”)
COMP103 – 2006/T3 3
A Linked Stack II
• Make the top of the Stack be the front of the list.
M
data
TOP
J
P C
A
H
• pop()
• stack = stack.push(“A”); M
• stack = stack.pop();
• But how do we return the value pop’d?
public LinkedStack(){ }
public E peek(){…
public E pop(){…
COMP103 – 2006/T3 7
LinkedStack
public boolean isEmpty(){
return data==null;
}
data
public int size () { M
if (data == null)
return 0; H
else
return data.size();
}
COMP103 – 2006/T3 8
LinkedStack
public E peek(){
if (data==null) throw new EmptyStackException();
return data.get();
} data
public E pop(){
if (data==null) throw new EmptyStackException();
E ans = data.get();
data = data.next();
return ans; M
}
public void push(E item){
if (item == null) throw new IllegalArgumentException();
data = new LinkedNode(item, data);
}
public Iterator <E> iterator(){ H
return new LinkedNodeIterator(data);
}
COMP103 – 2006/T3 9
LinkedNode methods
Size() returns number of nodes in list starting with this
node
B
OR
C
itr
node
H
COMP103 – 2006/T3 12
Linked Queue I
• Which is the front of the queue, which is the back?
M
back
J
P C
X
H Front
A
COMP103 – 2006/T3 13
A Linked Queue II
• Implement a Queue using a linked list.
M
Front
J
P C
Back
• poll() deQueue
A
M P
Front
X J
Back
• offer(“A”) (enQueue)
A
COMP103 – 2006/T3 15
LinkedQueue
public class LinkedQueue <E> implements AbstractQueue
<E> {
private LinkedNode<E> front = null;
private LinkedNode<E> back = null;
public LinkedQueue(){ }
public E peek(){…
public E poll(){…
Front
Front
A
Back
Back
COMP103 – 2006/T3 17
LinkedQueue
public boolean offer(E item){ M
if (item == null) return false; Front
if (front == null){
back = new LinkedNode(item, null);
Back
front = back; A
} else {
back.setNext(new LinkedNode(item, null));
back= back.next();
}
return true; Front
} Front
A Back
Back
COMP103 – 2006/T3 18
LinkedQueue
public E peek(){
if (front==null) return null; M
else return front.get(); Front
}
Back
A
public E poll(){
if (front==null) return null;
E ans = front.get();
front = front.next();
if (front==null) back = null; Front
return ans;
}
Front Back
A
Back
COMP103 – 2006/T3 19
Linked Stack and Queue
• Uses a “header node”
• contains link to head node, and maybe last node of
linked list
• management information about the data.
•COMP103
Next –Lecture:
2006/T3
Variations of Lists. 20