1class DoublyLinkedList {
2 //A node class for doubly linked list
3 class Node{
4 int item;
5 Node previous;
6 Node next;
7
8 public Node(int item) {
9 this.item = item;
10 }
11 }
12 //Initially, heade and tail is set to null
13 Node head, tail = null;
14
15 //add a node to the list
16 public void addNode(int item) {
17 //Create a new node
18 Node newNode = new Node(item);
19
20 //if list is empty, head and tail points to newNode
21 if(head == null) {
22 head = tail = newNode;
23 //head's previous will be null
24 head.previous = null;
25 //tail's next will be null
26 tail.next = null;
27 }
28 else {
29 //add newNode to the end of list. tail->next set to newNode
30 tail.next = newNode;
31 //newNode->previous set to tail
32 newNode.previous = tail;
33 //newNode becomes new tail
34 tail = newNode;
35 //tail's next point to null
36 tail.next = null;
37 }
38 }
39
40//print all the nodes of doubly linked list
41 public void printNodes() {
42 //Node current will point to head
43 Node current = head;
44 if(head == null) {
45 System.out.println("Doubly linked list is empty");
46 return;
47 }
48 System.out.println("Nodes of doubly linked list: ");
49 while(current != null) {
50 //Print each node and then go to next.
51 System.out.print(current.item + " ");
52 current = current.next;
53 }
54 }
55}
56class Main{
57 public static void main(String[] args) {
58 //create a DoublyLinkedList object
59 DoublyLinkedList dl_List = new DoublyLinkedList();
60 //Add nodes to the list
61 dl_List.addNode(10);
62 dl_List.addNode(20);
63 dl_List.addNode(30);
64 dl_List.addNode(40);
65 dl_List.addNode(50);
66
67 //print the nodes of DoublyLinkedList
68 dl_List.printNodes();
69 }
70}
71
1//insert link at the first location
2void insertFirst(int key, int data) {
3
4 //create a link
5 struct node *link = (struct node*) malloc(sizeof(struct node));
6 link->key = key;
7 link->data = data;
8
9 if(isEmpty()) {
10 //make it the last link
11 last = link;
12 } else {
13 //update first prev link
14 head->prev = link;
15 }
16
17 //point it to old first link
18 link->next = head;
19
20 //point first to new first link
21 head = link;
22}