用c语言创建一个带头结点的单链表。要求:此单链表长度为10;创建完成后,输出显示所创建单链表各结点的值。
时间: 2024-05-14 15:15:41 浏览: 21
好的,您的问题已经收到。以下是用 C 语言创建带头节点的单链表,长度为 10,并输出各节点值的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node, *LinkList;
int main(){
LinkList L;
L = (LinkList)malloc(sizeof(Node));
L->next = NULL;
for(int i=1; i<=10; i++){
Node *p;
p = (Node*)malloc(sizeof(Node));
p->data = i;
p->next = L->next;
L->next = p;
}
Node *p = L->next;
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
return 0;
}
```
希望这个代码能够帮助您!
相关问题
用C语言写一个带头结点的单链表,此单链表长度为 10;创建完成后,输出显示所创建单链表各结点的 值。
好的,这个问题我可以回答。以下是用C语言实现带头结点的单链表并显示各结点值的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义结点结构体
typedef struct node{
int data; // 数据域
struct node *next; // 指针域
}ListNode, *ListPtr;
// 创建单链表
ListPtr createList(int n) {
ListPtr head = (ListPtr)malloc(sizeof(ListNode)); // 创建头结点
if(head == NULL) { // 内存分配失败
printf("Memory allocation failed.\n");
exit(-1);
}
head->next = NULL; // 头结点指针域初始化为 NULL
ListPtr p = head; // 定义指针变量 p, 初始化为头结点
int i;
for(i = 0; i < n; i++) {
ListPtr newNode = (ListPtr)malloc(sizeof(ListNode)); // 创建新的结点
printf("Please enter the data of node %d: ", i+1);
scanf("%d", &(newNode->data)); // 读入结点数据
newNode->next = NULL; // 新结点的指针域初始化为 NULL
p->next = newNode; // 新结点添加到链表中
p = p->next; // p 指向链表尾结点
}
return head; // 返回链表头结点指针
}
// 输出单链表
void printList(ListPtr L) {
ListPtr p = L->next; // 指针变量 p 指向首结点
while(p != NULL) { // 遍历链表并输出每个结点的值
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
ListPtr L;
L = createList(10);
printf("The elements of the linked list are: ");
printList(L);
return 0;
}
```
运行代码后,程序会要求输入每个结点的数据,最后输出创建的单链表中每个结点的值。
用C语言写一个带头节点的单链表,此单链表长度为 10;创建完成后,输出显示所创建单链表各结点的 值
好的,我可以帮你解决这个问题。以下是用C语言写一个带头节点的单链表,长度为10,并输出各节点值的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
int main() {
int i;
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode)); // 创建头节点
head->next = NULL; // 头节点指向空
// 在链表中添加10个节点
for (i = 1; i <= 10; i++) {
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = i;
node->next = head->next; // 新节点的next指向头节点的next
head->next = node; // 头节点的next指向新节点
}
// 遍历单链表并输出各节点的值
struct ListNode *p = head->next;
while (p) {
printf("%d ", p->val);
p = p->next;
}
// 释放链表中所有节点所占用的空间
p = head;
while (p) {
struct ListNode *temp = p;
p = p->next;
free(temp);
}
return 0;
}
```
希望这个代码能够帮到你!如果你有其他问题需要帮助,请随时告诉我。