You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// DoublyLinkedList.javapublicclassDoublyLinkedList {
DNodehead;
DNodetail;
/** Insert at the last. It is faster with tail */voidinsert(intkey) {
DNodetemp = newDNode(key); // create the node to be inserted// Two cases to deal - List empty and otherwiseif (head == null) { // 1. List emptyhead = temp; // First node addedtail = head; // head and tail point to first node
}
else { // 2. List has at least one elementtail.next = temp; // Add temp after tailtemp.prev = tail;
tail = temp; // Make temp the new tail
}
}
voidprint() {
DNodecurr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
intsize() {
ints = 0;
DNodecurr = head;
while (curr != null) {
s++;
curr = curr.next;
}
returns;
}
/** Insert at a given position */voidinsert(intpos, intkey) {
DNodetemp = newDNode(key); // create the node to be inserted// Four cases cases to dealif (pos == 0 && head == null) { // 1. insert first when linked list is emptyhead = temp;
tail = head;
}
elseif (pos == 0 && head != null) { // 2. insert first when linked list is not emptytemp.next = head;
head.prev = temp;
head = temp;
}
elseif (pos >= size()) { // 3. position exceeds size - insert at the endtail.next = temp; // Add temp after tailtemp.prev = tail;
tail = temp; // Make temp the new tail
}
else { // 4. insert in betweenDNodecurr = head;
for (inti=0; i<pos-1; i++)
curr = curr.next; // Go to prior positiontemp.next = curr.next; // Reassign the pointerscurr.next.prev = temp;
curr.next = temp;
temp.prev = curr;
}
}
/** Search if key is present in the linked list */intsearch(intkey) {
DNodecurr = head;
intpos = 0;
while (curr != null) { // Till the end if ( curr.data == key) // key is foundreturnpos;
else { // continue if key is not foundcurr = curr.next;
pos++;
}
}
return -1; // key was never found
}
/** Delete the node containing key */voiddelete(intkey) {
intpos = search(key); // find the pos of the keySystem.out.println(pos + " " + size());
// Four cases to be dealt with based on posif (pos == -1) // 1. key not found, so nothing to deletereturn;
if (pos == 0) { // 2. first node to be deleted, second node becomes the headhead = head.next;
return;
}
if (pos == size()-1) { // 3. last node to be deleted, reassign tail to previous nodeDNodecurr = tail;
curr = curr.prev;
tail.prev = null;
curr.next = null;
tail = curr;
return;
}
// 4. Navigate till the prior node of the to-be-deleted nodeDNodecurr = head;
for (inti=0; i<pos-1; i++)
curr = curr.next;
// temp is the node to be deleted (next to curr)DNodetemp = curr.next;
curr.next = temp.next; // reassign the linkstemp.next = null;
}
}