Java中单链表和双链表的区别
单链表和双链表都是链表的实现,其中单链表的每个元素都包含一些数据以及到下一个元素的链接,从而可以保持结构。另一方面,双向链接列表中的每个节点也包含指向前一个节点的链接。
以下是单链接列表和双链接列表之间的重要区别。
单链表与双链表的示例
SinlgyLinkedList.java
class Node { //创建类Node- public int data; public Node next; //create node parameter for pointer of next element public void displayNodeData() { System.out.println("{ " + data + " } "); } } public class SinglyLinkedList { private Node head; public boolean isEmpty() { return (head == null); } //用于在链表的开头插入节点 public void insertFirst(int data) { Node newNode = new Node(); newNode.data = data; newNode.next = head; head = newNode; } //用于从链表的开头删除节点 public Node deleteFirst() { Node temp = head; head = head.next; return temp; } //用于删除特定节点之后的节点 public void deleteAfter(Node after) { Node temp = head; while (temp.next != null && temp.data != after.data) { temp = temp.next; } if (temp.next != null) temp.next = temp.next.next; } //用于在链表的开头插入节点 public void insertLast(int data) { Node current = head; while (current.next != null) { current = current.next; // we'll loop until current.next is null } Node newNode = new Node(); newNode.data = data; current.next = newNode; } //用于打印链表 public void printLinkedList() { System.out.println("Printing LinkedList (head --> last) "); Node current = head; while (current != null) { current.displayNodeData(); current = current.next; } System.out.println(); } }
示例
LinkedListMain.java
public class LinkedListMain { public static void main(String args[]){ SinglyLinkedList myLinkedlist = new SinglyLinkedList(); myLinkedlist.insertFirst(5); myLinkedlist.insertFirst(6); myLinkedlist.insertFirst(7); myLinkedlist.insertFirst(1); myLinkedlist.insertLast(2); Node node=new Node(); node.data=1; myLinkedlist.deleteAfter(node); myLinkedlist.printLinkedList(); } }
输出结果
Printing LinkedList (head --> last) { 1 } { 6 } { 5 } { 2 }
示例
DoublyLinkedListMain.java
public class DoublyLinkedList { class Node{ int data; Node previous; Node next; public Node(int data) { this.data = data; } } Node head, tail = null; public void addNode(int data) { //创建一个新节点 Node newNode = new Node(data); if(head == null) { head = tail = newNode; head.previous = null; tail.next = null; } else { tail.next = newNode; newNode.previous = tail; tail = newNode; 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) { System.out.print(current.data + " "); current = current.next; } } public static void main(String[] args) { DoublyLinkedList dList = new DoublyLinkedList(); dList.addNode(1); dList.addNode(2); dList.addNode(3); dList.addNode(4); dList.addNode(5); dList.display(); } }
输出结果
Nodes of doubly linked list: 1 2 3 4 5