创建包含n个节点的单向链表
时间: 2023-09-20 12:04:37 浏览: 34
好的,以下是创建包含n个节点的单向链表的示例代码(使用Java语言实现):
```java
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode createLinkedList(int n) {
ListNode head = new ListNode(1); // 创建头节点
ListNode tail = head; // 将尾指针指向头节点
for(int i = 2; i <= n; i++) {
ListNode newNode = new ListNode(i); // 创建新节点
tail.next = newNode; // 将新节点添加至链表末尾
tail = newNode; // 更新尾指针
}
return head; // 返回头节点
}
public static void main(String[] args) {
int n = 5;
Solution s = new Solution();
ListNode head = s.createLinkedList(n);
ListNode p = head;
while(p != null) {
System.out.print(p.val + " ");
p = p.next;
}
}
}
```
这段代码会创建包含5个节点的单向链表,并将其打印输出。你可以根据需要更改n的值来创建不同节点数目的链表。