|
| 1 | + |
1 | 2 | /**
|
2 | 3 | * This class implements a DoublyLinkedList. This is done using the classes
|
3 | 4 | * LinkedList and Link.
|
@@ -62,34 +63,45 @@ public void insertHead(int x){
|
62 | 63 | publicvoidinsertTail(intx){
|
63 | 64 | LinknewLink =newLink(x);
|
64 | 65 | newLink.next =null;// currentTail(tail) newlink -->
|
65 |
| -tail.next =newLink;// currentTail(tail) --> newLink --> |
66 |
| -newLink.previous =tail;// currentTail(tail) <--> newLink --> |
67 |
| -tail =newLink;// oldTail <--> newLink(tail) --> |
| 66 | +if(isEmpty()) {// Check if there are no elements in list then it adds first element |
| 67 | +tail=newLink; |
| 68 | +head=tail; |
| 69 | +} |
| 70 | +else { |
| 71 | +tail.next =newLink;// currentTail(tail) --> newLink --> |
| 72 | +newLink.previous =tail;// currentTail(tail) <--> newLink --> |
| 73 | +tail =newLink;// oldTail <--> newLink(tail) --> |
| 74 | +} |
68 | 75 | }
|
69 | 76 |
|
70 | 77 | /**
|
71 | 78 | * Delete the element at the head
|
72 | 79 | *
|
73 | 80 | * @return The new head
|
74 | 81 | */
|
75 |
| -publicvoiddeleteHead(){ |
| 82 | +publicLinkdeleteHead(){ |
76 | 83 | Linktemp =head;
|
77 | 84 | head =head.next;// oldHead <--> 2ndElement(head)
|
78 | 85 | head.previous =null;// oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
|
79 | 86 | if(head ==null)
|
80 | 87 | tail =null;
|
| 88 | +returntemp; |
81 | 89 | }
|
82 | 90 |
|
83 | 91 | /**
|
84 | 92 | * Delete the element at the tail
|
85 | 93 | *
|
86 | 94 | * @return The new tail
|
87 | 95 | */
|
88 |
| -publicvoiddeleteTail(){ |
| 96 | +publicLinkdeleteTail(){ |
89 | 97 | Linktemp =tail;
|
90 | 98 | tail =tail.previous;// 2ndLast(tail) <--> oldTail --> null
|
91 | 99 | tail.next =null;// 2ndLast(tail) --> null
|
92 |
| - |
| 100 | +if(tail==null) |
| 101 | + { |
| 102 | +head=null; |
| 103 | + } |
| 104 | +returntemp; |
93 | 105 | }
|
94 | 106 |
|
95 | 107 | /**
|
|