用java定义一个链表数据结构
时间: 2023-11-26 19:00:53 浏览: 38
好的,以下是用Java定义一个链表数据结构的例子:
```
public class LinkedList {
Node head; // 链表头节点
static class Node {
int data; // 此节点存储的数据
Node next; // 下一个节点
Node(int d) { // 构造函数
data = d;
next = null;
}
}
// 添加新节点到链表末尾
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
// 在指定位置插入节点
public void insert(int data, int position) {
Node newNode = new Node(data);
if (position == 0) {
newNode.next = head;
head = newNode;
return;
}
Node previous = null;
Node current = head;
for (int i = 0; i < position; i++) {
previous = current;
current = current.next;
if (current == null) {
break;
}
}
newNode.next = current;
previous.next = newNode;
}
// 删除指定位置的节点
public void delete(int position) {
if (head == null) {
return;
}
Node current = head;
if (position == 0) {
head = head.next;
return;
}
Node previous = null;
for (int i = 0; i < position; i++) {
previous = current;
current = current.next;
if (current == null) {
return;
}
}
previous.next = current.next;
}
// 打印链表中的所有节点
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
```
以上就是一个简单的链表数据结构的定义,可以用来存储整数型数据。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)