public class DoublyLinkedList { Node Head; // head of Doubly Linked List //Doubly Linked list Node class Node { int value; Node prev; Node next; // Constructor to create a new node Node(int d) { value = d; } } // Inserting a node at the front of the list public void add(int newData) { // allocate node and put in the data Node newNode = new Node(newData); // Make the next of new node as head // and previous as NULL newNode.next = Head; newNode.prev = null; //change prev of head node to the new node if (Head != null) Head.prev = newNode; //move the head to point to the new node Head = newNode; } // Function to delete a node in a Doubly Linked List. void remove(Node del) { // Base case if (Head == null || del == null) { return; } // If node to be deleted is head node if (Head == del) { Head = del.next; } // When node to be deleted is not // the last node, change next. if (del.next != null) { del.next.prev = del.prev; } // When node to be removed is not the first node, // change prev. if (del.prev != null) { del.prev.next = del.next; } return; } //Function to display Doubly Linked List content public void display(Node node) { Node last = null; while (node != null) { System.out.print(node.value + " "); last = node; node = node.next; } System.out.println(); } public static void main(String[] args) { // Initiallize the Doubly Linked List DoublyLinkedList d = new DoublyLinkedList(); // add 6. d.add(6); // add 19. d.add(19); // add 2. d.add(2); // add 15. d.add(15); System.out.print("Doubly Linked List "); d.display(d.Head); // Removing first node d.remove(d.Head); // List after removing first node // 2->19->6 System.out.print("\nDoubly Linked List after removing first node: "); d.display(d.Head); // Removing middle node from 2->19->6 d.remove(d.Head.next); System.out.print("\nDoubly Linked List after removing middle node: "); d.display(d.Head); } }
WRITE THE UML DIAGRAM AND PSEUDO CODE
The UML Class diagram is:
The pseudocode is given as:
Pseudocode
Each Node of the doubly linked list consists of the data value, a pointer pointing to the previous element and a next pointer pointing to the next element.
// add method inserts a node at the front of the list
function add (newData) {
newNode = Node(newData); // create a new node with the given data
newNode.next = Head
newNode.prev = null
if Head is not null then
Head.prev = newNode
end if
Head = newNode
}
// this function deletes a node in a Doubly Linked List.
function remove(del){
if (Head is null or del is null) then
return
end if
if Head is same as del) then
Head = del.next
end if
if (del.next is not null) then
del.next.prev = del.prev
end if
if (del.prev is not null) then
del.prev.next = del.next
end if
}
// display() displays Doubly Linked List content
function display(node) {
last = null
run till (node is not null) do
print node.value
last = node
node = node.next
end loop
}
System.out.println();
}
Get Answers For Free
Most questions answered within 1 hours.