c++尾插法建立单链表
时间: 2023-04-03 11:02:52 浏览: 164
尾插法建立单链表是一种常用的方法,可以通过循环不断地向链表尾部添加新节点来构建链表。具体实现方法是,先创建一个头节点,然后循环读入数据,每次创建一个新节点,将数据存入新节点中,再将新节点插入到链表尾部。最后返回头节点即可。
相关问题
c++尾插法建立单链表代码
以下是尾插法建立单链表的 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;
}
```
C++用尾插法建立单链表代码
很高兴回答您的问题,以下是使用尾插法建立单链表的 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, val;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个节点的值:", i + 1);
scanf("%d", &val);
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = val;
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() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("链表的值为:");
printList(head);
return 0;
}
```
希望能够帮助您!
阅读全文