單鏈表是一種常用的數據結構,它由一個一個節點組成,每個節點都有一個指向下一個節點的引用。Java中實現單鏈表需要創建一個單鏈表類,如下所示:
public class LinkedList { private Node head; private class Node { private int data; private Node next; public Node(int data, Node next) { this.data = data; this.next = next; } public int getData() { return data; } public Node getNext() { return next; } } public void add(int data) { head = new Node(data, head); } public boolean contains(int data) { Node node = head; while (node != null) { if (node.data == data) { return true; } node = node.next; } return false; } public void remove(int data) { if (head == null) { return; } if (head.data == data) { head = head.next; return; } Node prev = head; Node current = head.next; while (current != null) { if (current.data == data) { prev.next = current.next; return; } prev = current; current = current.next; } } }
上面的代碼實現了一個基本的單鏈表,可以添加、移除和查找元素。但單鏈表有一個缺陷,每個節點只能訪問它的下一個節點,無法訪問前面的節點。為了解決這個問題,我們可以使用雙鏈表。
雙鏈表和單鏈表類似,但每個節點除了指向下一個節點的引用外,還有指向前一個節點的引用。Java中實現雙鏈表需要創建一個雙鏈表類,如下所示:
public class DoublyLinkedList { private Node head; private class Node { private int data; private Node prev; private Node next; public Node(int data, Node prev, Node next) { this.data = data; this.prev = prev; this.next = next; } public int getData() { return data; } public Node getPrev() { return prev; } public Node getNext() { return next; } } public void add(int data) { Node newNode = new Node(data, null, head); if (head != null) { head.prev = newNode; } head = newNode; } public boolean contains(int data) { Node node = head; while (node != null) { if (node.data == data) { return true; } node = node.next; } return false; } public void remove(int data) { Node node = head; while (node != null && node.data != data) { node = node.next; } if (node == null) { return; } if (node.prev == null) { head = node.next; } else { node.prev.next = node.next; } if (node.next != null) { node.next.prev = node.prev; } } }
上面的代碼實現了一個基本的雙鏈表,可以添加、移除和查找元素。雙鏈表比單鏈表多了一個指向前一個節點的引用,因此可以從前往后遍歷也可以從后往前遍歷。