创建一个带头结点的长度为 10的单链表。创建完成后,输出显示所创建单链表各结点的 值。
时间: 2024-05-04 09:16:28 浏览: 18
好的,我可以帮你回答这个问题。以下是创建一个带头结点的长度为10的单链表的代码,以及输出所创建单链表各结点的值的代码:
```python
# 定义一个单链表节点的类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 创建一个带头结点的长度为10的单链表并输出各节点的值
def create_linked_list():
# 创建头节点
head = ListNode()
cur = head
# 创建10个节点
for i in range(1,11):
node = ListNode(i)
cur.next = node
cur = cur.next
# 遍历链表并输出各节点的值
cur = head.next
while cur:
print(cur.val, end=" ")
cur = cur.next
create_linked_list()
```
运行以上代码,就可以创建一个带头结点的长度为10的单链表,并且输出所创建单链表各结点的值。
输出结果:
```
1 2 3 4 5 6 7 8 9 10
```
相关问题
用C++语言创建一个带头结点的单链表.此单链表长度为 10,创建完成后,输出显示所创建单链表各结点的 值
好的,您可以使用以下代码创建一个带头结点的长度为10的单链表,并输出各结点的值:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义单链表结点 */
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
/* 创建单链表 */
ListNode* createList(int len) {
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); // 创建头结点
head->next = NULL; // 头结点的next指针初始化为NULL
ListNode* cur = head; // 定义指针cur指向头结点
for(int i = 0; i < len; i++) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode)); // 创建新结点
node->val = i + 1; // 新结点的值为i + 1
node->next = NULL; // 新结点的next指针初始化为NULL
cur->next = node; // 当前结点的next指针指向新结点
cur = node; // 指针cur指向新结点
}
return head;
}
/* 输出单链表各结点的值 */
void printList(ListNode* head) {
ListNode* cur = head->next; // 定义指针cur指向第一个结点
while(cur != NULL) {
printf("%d ", cur->val); // 输出结点的值
cur = cur->next; // cur指针后移
}
printf("\n");
}
int main() {
ListNode* head = createList(10); // 创建长度为10的单链表
printList(head); // 输出各结点的值
return 0;
}
```
以上就是用 C 语言创建一个带头结点的单链表并输出各结点的值的代码。感谢您的提问!
创建一个带头结点的单链表。要求:此单链表长度为10;创建完成后,输出显示所创建单链表各结点的值。
好的,您的要求我已经记住了,我可以用Python语言来创建带头结点的单链表,代码如下:
```python
# 定义节点类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 创建带头结点的单链表
head = ListNode(-1)
cur = head
for i in range(10):
cur.next = ListNode(i+1)
cur = cur.next
# 输出所创建单链表各结点的值
cur = head.next
while cur:
print(cur.val, end=' ')
cur = cur.next
```
以上代码创建了一个带头结点的单链表,长度为10,并且输出了每个节点的值。希望我的回答对您有所帮助。
相关推荐
![](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)