java实现双向链表
时间: 2023-09-17 18:08:05 浏览: 95
Java实现双向链表
Java可以通过定义一个双链表类来实现双向链表。下面是一个示例的Java代码来实现一个双链表:
```java
package DoubleLinkedListTwo;
//定义一个节点类
class ListNode {
int val;
ListNode prev;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
//定义双链表类
public class DoubleLinkedList {
private ListNode head; //头节点
//在链表末尾添加一个节点
public void addLast(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
head = newNode;
} else {
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newNode;
newNode.prev = cur;
}
}
//打印双链表
public void display() {
ListNode cur = head;
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
}
//清空链表
public void clear() {
head = null;
}
}
//测试双链表
public class TestDoubleLinkedList {
public static void main(String[] args) {
//创建一个双链表
DoubleLinkedList d = new DoubleLinkedList();
//在链表末尾添加元素
d.addLast(1);
d.addLast(1);
d.addLast(1);
d.addLast(1);
//打印链表
d.display();
//清空链表
d.clear();
d.display();
}
}
```
以上代码示例演示了如何使用Java代码实现一个双向链表,并在双链表中添加元素,并打印链表。你可以根据自己的需求进一步扩展这个双链表类,并在测试类中添加其他操作,如在指定位置插入元素、删除元素等。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Java 实现 双向链表](https://blog.csdn.net/m0_52066789/article/details/122342307)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文