C语言创建带头结点的链表的代码
时间: 2023-04-11 11:00:55 浏览: 198
以下是创建带头结点的链表的 C 语言代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList() {
Node *head = (Node *) malloc(sizeof(Node));
head->next = NULL;
return head;
}
void insert(Node *head, int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = head->next;
head->next = newNode;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList();
insert(head, 1);
insert(head, 2);
insert(head, 3);
printList(head);
return 0;
}
```
阅读全文