c++尾插法建立单链表代码
时间: 2023-04-03 14:02:52 浏览: 91
尾插法单链表的建立
以下是尾插法建立单链表的 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
int i, num;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个节点的值:", i + 1);
scanf("%d", &num);
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
int main() {
int n;
printf("请输入链表的节点数:");
scanf("%d", &n);
Node *head = createList(n);
printf("链表的值为:");
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
阅读全文