单链表不带头节点的建表
时间: 2023-05-15 08:05:44 浏览: 48
可以使用如下代码实现单链表不带头节点的建表:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList() {
Node *head = NULL, *tail = NULL;
int x;
while (scanf("%d", &x) == 1) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = createList();
printList(head);
return 0;
}
```
这段代码可以从标准输入中读入一些整数,然后创建一个单链表并返回头节点。在创建链表时,我们使用了一个尾指针 tail 来记录链表的尾部,这样可以避免每次插入都需要遍历整个链表。最后,我们可以使用 printList 函数来打印链表的所有元素。