- best implemented with linked lists
- trying to implement with arrays or arraylists is not feasible
Doubly Linked Lists
- in a double linked list keep track of
- head
- next pointer in each node
- tail
- previous pointer of each node
public class DoubleLinkedList
{
public class ListNode
{
private myObject item;
private ListNode next;
private ListNode prev;
public ListNode {...}
}
public void addNode(MyObject, int)
public void delNode(int)
public myObject getData(int)
public void addNodeToHead(MyObject a)
public void addNodeToTail(MyObject b)
public void delNodeFromHead()
public void delNodeFromTail()
public MyObject getDataFromHead()
public MyObject getDataFromTail()
Adding a Node to A Position
//ListNode c = a.next;
b.next = a.next;
b.prev = a;
(a.next).prev = b;
a.next = b
//c.prev = b;
if (a==tail)
{tail=b;}
More Formally
//Check whether a exists
if (a != null)
{
b.next = a.next;
b.prev = a;
a.next = b;
if (a==tail){tail = b;}
else{
(b.next).prev = b
}
Deleting a Node From a Given Position
if(a.next)!= null
{
if (a.next = tail)
{a.next = null;
tail = a}
else{
a.next = (a.next).next
(a.next).prev = a;
}
}
Doubly linked list with stacks and queues
- Stack
- add
- addNodeToHead(MyObject)
- delete
- getDataFromHead()
- delNodeFromHead()
- Queue
- add a
- addNodeToHead(MyObject)
- delete / leave
- getDataFromTail
- delNodeFromTail()
No comments:
Post a Comment