Presentation is loading. Please wait.

Presentation is loading. Please wait.

Header and Trailer Sentinels

Similar presentations


Presentation on theme: "Header and Trailer Sentinels"— Presentation transcript:

1

2 Header and Trailer Sentinels
Helps to add special nodes at both ends of the list: a header node at the beginning of the list, and a trailer node at the end of the list. These “dummy” nodes are known as sentinels (or guards), and they do not store elements It avoids some special cases when operating near the boundaries of a doubly linked list

3

4 Advantage we can treat all insertions in a unified manner, because a new node will always beplaced between a pair of existing nodes. In similar fashion, every element that is to be deleted is guaranteed to be stored in a node that has neighbors on each side.

5 Adding nodes(AddFirst())

6 Adding in between

7 size( ): Returns the number of elements in the list.
isEmpty( ): Returns true if the list is empty, and false otherwise. first( ): Returns (but does not remove) the first element in the list. last( ): Returns (but does not remove) the last element in the list. addFirst(e): Adds a new element to the front of the list. addLast(e): Adds a new element to the end of the list. removeFirst( ): Removes and returns the first element of the list. removeLast( ): Removes and returns the last element of the list.

8 Class dnode { int data; node prev, next; public node(int x, node t1, node t2) data=x; prev=t1; next=t2; }

9 private void addBetween(int x, node predecessor, node successor) { node temp = new node(x, predecessor, successor); Predecessor.next=temp; Successor.prev=temp; }

10 int removeNode(node p) { node predecessor = p.prev; node successor = p.next; predecessor.next=successor; successor.prev=predecessor; return p.data; }

11 public void addFirst(int x) { addBetween(x, header, header
public void addFirst(int x) { addBetween(x, header, header.next); } addLast(int x) { addBetween(x, trailer.prev, trailer);

12 public int removeFirst( )
{ if (isEmpty( )) return null; return removeNode(header.next); } public int removeLast( ) return removeNode(trailer.prev);


Download ppt "Header and Trailer Sentinels"

Similar presentations


Ads by Google