Both singly-linked lists and doubly-linked lists are linear data structures that store a collection of elements. However, the key difference between them is the number of links between each node and its neighboring nodes.
A singly-linked list is a linear data structure in which each node contains a value and a single link pointing to the next node in the list. The last node in the list has a link pointing to null, indicating the end of the list. Here is an example of a singly-linked list:
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
}
class SinglyLinkedList {
Node head;
public SinglyLinkedList() {
this.head = null;
}
public void add(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
}
In this example, the Node class represents a node in the singly-linked list, with an integer value and a single link pointing to the next node in the list. The SinglyLinkedList class represents the singly-linked list itself, with a head node and a method for adding nodes to the end of the list.
A doubly-linked list, on the other hand, is a linear data structure in which each node contains a value and two links, one pointing to the previous node and one pointing to the next node in the list. The first node in the list has a link pointing to null for the previous node, and the last node in the list has a link pointing to null for the next node. Here is an example of a doubly-linked list:
class Node {
int value;
Node prev;
Node next;
public Node(int value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
Node head;
Node tail;
public DoublyLinkedList() {
this.head = null;
this.tail = null;
}
public void add(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
}
In this example, the Node class represents a node in the doubly-linked list, with an integer value and two links pointing to the previous node and the next node in the list. The DoublyLinkedList class represents the doubly-linked list itself, with a head node, a tail node, and a method for adding nodes to the end of the list.
In summary, the main difference between a singly-linked list and a doubly-linked list is that a singly-linked list has a single link pointing to the next node, while a doubly-linked list has two links pointing to the previous node and the next node. A doubly-linked list provides more flexibility in terms of traversing the list in both forward and backward directions, but requires more memory to store the extra links.