建立一个带头结点的线性链表
时间: 2023-05-13 11:06:03 浏览: 56
好的,以下是建立一个带头结点的线性链表的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
for (int i = 0; i < n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &(newNode->data));
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
return head;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("链表的值为:");
printList(head);
return 0;
}
```
希望这个代码能够帮到你!