c语言用尾插法实现链表创建
时间: 2024-11-23 07:40:21 浏览: 82
C语言中,链表是一种常见的数据结构,尾插法(也叫尾部插入)是指在创建链表的时候,新节点总是添加到当前链表的最后一个元素之后。这种操作不需要预先计算链表的长度,常用于动态增长的数据集合。
下面是一个简单的示例,展示如何用C语言的尾插法创建单向链表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
// 创建新节点并插入链尾
Node* insertAtTail(Node** head, int value) {
if (*head == NULL) { // 链表为空的情况
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
*head = newNode;
return newNode;
} else {
Node* newNode = (Node*)malloc(sizeof(Node)); // 新节点
newNode->data = value;
newNode->next = NULL; // 初始化新节点的next指向NULL
Node* current = *head; // 从头开始遍历链表
while (current->next != NULL) {
current = current->next; // 当前节点移到下一个
}
current->next = newNode; // 将新节点插入到最后
return *head;
}
}
// 打印链表
void printList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
head = insertAtTail(&head, 1);
head = insertAtTail(&head, 2);
head = insertAtTail(&head, 3);
printf("Tail-inserted linked list: ");
printList(head); // 输出:1 2 3
return 0;
}
```
在这个例子中,`insertAtTail`函数接收一个指向链表头的指针,并在链表结尾处插入新值。当链表为空时,直接新建一个节点;否则,从头开始遍历链表直到找到最后一个节点,然后将新节点添加其后。
阅读全文
相关推荐

















