Java的链表是一种线性数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针,链表可以分为单向链表、双向链表和循环链表等类型。
1、单向链表
单向链表是最简单的链表类型,每个节点只有一个指向下一个节点的指针,下面是一个简单的单向链表实现:
class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } class LinkedList { Node head; public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } public void display() { Node current = head; while (current != null) { System.out.print(current.data + " > "); current = current.next; } System.out.println("null"); } }
2、双向链表
双向链表与单向链表类似,但每个节点有两个指针,一个指向前一个节点,一个指向后一个节点,下面是一个简单的双向链表实现:
class DoublyNode { int data; DoublyNode prev; DoublyNode next; public DoublyNode(int data) { this.data = data; this.prev = null; this.next = null; } } class DoublyLinkedList { DoublyNode head; DoublyNode tail; public void add(int data) { DoublyNode newNode = new DoublyNode(data); if (head == null) { head = newNode; tail = newNode; } else { tail.next = newNode; newNode.prev = tail; tail = newNode; } } public void display() { DoublyNode current = head; while (current != null) { System.out.print(current.data + " <> "); current = current.next; } System.out.println("null"); } }
3、循环链表
循环链表是一种特殊的链表,它的最后一个节点的指针指向第一个节点,形成一个环,下面是一个简单的循环链表实现:
class CircularDoublyNode { int data; CircularDoublyNode prev; CircularDoublyNode next; public CircularDoublyNode(int data) { this.data = data; this.prev = null; this.next = null; } } class CircularDoublyLinkedList { CircularDoublyNode head; CircularDoublyNode tail; public void add(int data) { CircularDoublyNode newNode = new CircularDoublyNode(data); if (head == null) { head = newNode; tail = newNode; head.next = head; // 形成环的指针指向自己(头结点)和尾结点(头结点)的指针都指向头结点(尾结点)形成环状结构。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/641852.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复