Explanation
In this program, we will create a doubly linked list and insert every new node at the end of the list. If the list is empty, then head and tail will point to newly added node. If list is not empty then, insert the new node at the end of the list such that tail's next will point to new node. Make new node as new tail of the list and its next will point to null.
In above example, node 4 was the tail of the list. Now, the new node will be inserted at the end of the list such that node 4's next will point to new node. Make new node as the tail of the list, and its next will point to null.
Algorithm
- Define a Node class which represents a node in the list. It will have three properties: data, previous which will point to the previous node and next which will point to the next node.
- Define another class for creating a doubly linked list, and it has two nodes: head and tail. Initially, head and tail will point to null.
- addAtEnd() will add node to the list:
- It first checks whether the head is null, then it will insert the node as the head.
- Both head and tail will point to a newly added node.
- Head's previous pointer will point to null and tail's next pointer will point to null.
- If the head is not null, the new node will be inserted at the end of the list such that new node's previous pointer will point to tail.
- The new node will become the new tail. Tail's next pointer will point to null.
- display() will show all the nodes present in the list.
- Define a new node 'current' that will point to the head.
- Print current.data till current points to null.
- Current will point to the next node in the list in each iteration.
Input:
#Adding 1 to the list
dList.addAtEnd(1);
#Adding 2 to the list
dList.addAtEnd(2);
#Adding 3 to the list
dList.addAtEnd(3);
#Adding 4 to the list
dList.addAtEnd(4);
#Adding 5 to the list
dList.addAtEnd(5);
Output:
Adding a node to the end of the list: 1
Adding a node to the end of the list: 1 2
Adding a node to the end of the list: 1 2 3
Adding a node to the end of the list: 1 2 3 4
Adding a node to the end of the list: 1 2 3 4 5
Python
Output:
C
Output:
JAVA
Output:
C#
Output:
PHP
Output: