双向链表的创建Java
时间: 2023-09-17 15:06:35 浏览: 43
下面是双向链表的创建Java代码示例:
```java
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
Node head;
Node tail;
public void addNode(int data) {
Node newNode = new Node(data);
if(head == null) {
head = tail = newNode;
head.prev = null;
tail.next = null;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
tail.next = null;
}
}
public void display() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.addNode(10);
list.addNode(20);
list.addNode(30);
list.addNode(40);
System.out.println("Doubly linked list:");
list.display();
}
}
```
在上面的示例代码中,我们首先定义了一个 `Node` 类来表示链表的节点,其中包含了数据、前驱节点和后继节点。然后定义了一个 `DoublyLinkedList` 类,其中包含了链表的头节点和尾节点。接着,我们定义了 `addNode()` 方法来向链表中添加节点,并且根据链表是否为空来进行不同的操作。最后,我们定义了 `display()` 方法来遍历链表并输出节点的数据。在 `main()` 方法中,我们创建了一个 `DoublyLinkedList` 对象,并向其中添加了一些节点,并输出整个双向链表。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)