A singly linked list, because it also needs to maintain the pointers to the other nodes, which takes up space.
The linked list should have a tail pointer in addition to a head pointer.
An alternative to a standard deletion strategy is known as lazy deletion. When deleting elements from a singly linked list, we delete them logically but not physically. This is done by marking the node as deleted (using a boolean value). The numbers of deleted and not-deleted elements in the list are kept as part of the list. If at some point the number of deleted elements is equal to the number of not-deleted elements, we traverse the list and delete all "lazily deleted" elements. Discuss the advantages and disadvantages of this scheme.
Advantages: It takes less time to mark a node as deleted than to change pointers.
Disadvantages: Once a node has been "lazily deleted" it still needs to be traversed in a search for another node. Also, you then use up a lump amount of time to delete all the "lazily deleted elements".
Assuming the linked list above, provide the output for the following code fragments.
The list is restored to its initial state before each line executes:
a) ____5_____
head.next.next.next.data;
b) ____3_____
head.next.next.prev.prev.data;
c) ____9_____
tail.prev.prev.prev.next.data;
Write the statements to insert a new node
Node toInsert = new Node(6);
nextNode = prevNode.getNext(); //now nextNode is 5 prevNode.setNext(toInsert); //prevNode is 9 nextNode.setPrev(toInsert); toInsert.setNext(nextNode); toInsert.setPrev(prevNode);
public void removeAllMatchingItems(AnyType keyItem)
that removes each and every item equal the keyItem from a singly-linked list. The list is not changed in any other way - if the requested item is not contained within the list, the method leaves the list in its prior condition You assume the LinkedList class given in lectures.
public void removeAllMatchingItems(AnyType keyItem){ if(list == null) return; if(head == null) return; while(head != null && head.data.equals(keyItem)){ head = head.next; } Node temp = head; Node prev = head; while(temp != null){ if(temp.data.equals(keyItem)){ prev.next = temp.next; }else{ prev = temp; } temp = temp.next; } }
public void insertInOrder(Comparable keyItem)
that creates a new node and inserts it in-order into the list. You assume the LinkedList class given in lectures.
public void insertInOrder(Comparable keyItem){ Node newNode = new Node(keyItem); if(head == null){ head = newNode; return; } Node temp = head; Node prev = head; while(temp != null && temp.data.compareTo(keyItem)>0){ prev = temp; temp = temp.next; } prev.next = newNode; newNode.next = temp; }