In: Computer Science
Using Doubly Linked List, create a java code that does the following Without using LinkedList from the JAVA LIBRARY. and please include methods for each function.
Create a menu that contains the following operations :
1. Add new node to DLL. ( as a METHOD )
2. Delete a node from DLL. ( as a METHOD )
3. Show how many nodes in DLL. ( as a METHOD )
4. Print all data in the DLL. ( as a METHOD )
5. Exit.
Important notes :
1. Write the operations from the pseudocode.
2. The user should insert all data even in the first node.
3. The menu should be repeated each time until the user 5 (Exit).
Code - JAVA
DoublyLinkedList.java
public class DoublyLinkedList {
class Node{
int data;
Node previous;
Node next;
public Node(int data) {
this.data = data;
}
}
//Represent the head and tail of the doubly linked list
Node head, tail = null;
//addNode() will add a node to the list
public void addNode(int data) {
//Create a new node
Node newNode = new Node(data);
//If list is empty
if(head == null) {
//Both head and tail will point to newNode
head = tail = newNode;
//head's previous will point to null
head.previous = null;
//tail's next will point to null, as it is the last node of the list
tail.next = null;
}
else {
//newNode will be added after tail such that tail's next will point to newNode
tail.next = newNode;
//newNode's previous will point to tail
newNode.previous = tail;
//newNode will become new tail
tail = newNode;
//As it is last node, tail's next will point to null
tail.next = null;
}
}
public void display() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while(current != null) {
//Prints each node by incrementing the pointer.
System.out.print(current.data + " ");
current = current.next;
}
}
public void count_nodes() {
Node current = head;
int count=0;
while(current!=NULL) {
count++;
}
return count;
}
public static void main(String[] args) {
DoublyLinkedList dList = new DoublyLinkedList();
//Add nodes to the list
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
dList.display();
dList.count_nodes();
}
}
Note: If you have any doubts or any queries, feel free to ask
And if you like my answer, kindly upvote.
have a nice day