Java1.创建带头结点单链表,调用输出函数,输出单链表
时间: 2024-06-12 20:08:57 浏览: 126
可以按照以下步骤创建一个带头结点的单链表,并调用输出函数将其输出。
首先,创建一个节点类Node,包括数据域和指针域。
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
```
然后,创建一个链表类LinkedList,包含头结点和输出函数。
```java
class LinkedList {
Node head;
public LinkedList() {
this.head = new Node(0); // 创建头结点,默认值为0
}
public void addNode(int data) {
Node newNode = new Node(data);
Node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newNode;
}
public void printList() {
Node curr = head.next;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
}
```
接下来,我们可以创建一个LinkedList对象,并通过addNode方法添加节点数据,最后通过printList方法输出单链表。
```java
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
System.out.println("单链表内容:");
list.printList();
}
}
```
这样就可以创建一个带头结点的单链表,并调用输出函数将其输出。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)