c语言单链表程序代码怎么写
导读:以下是一个简单的C语言单链表的程序代码示例: #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 struct Node { int data;...
以下是一个简单的C语言单链表的程序代码示例:
#include stdio.h>
#include stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
}
;
// 在链表末尾插入新节点
void insertAtEnd(struct Node** head, int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->
data = data;
newNode->
next = NULL;
// 如果链表为空,则新节点为头节点
if (*head == NULL) {
*head = newNode;
}
else {
// 找到链表末尾并插入新节点
struct Node* current = *head;
while (current->
next != NULL) {
current = current->
next;
}
current->
next = newNode;
}
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->
data);
current = current->
next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 依次插入节点
insertAtEnd(&
head, 1);
insertAtEnd(&
head, 2);
insertAtEnd(&
head, 3);
insertAtEnd(&
head, 4);
// 打印链表
printf("链表:");
printList(head);
return 0;
}
这个程序演示了如何创建一个单链表并插入节点。在 insertAtEnd
函数中,我们创建一个新节点并将其插入到链表的末尾。在 printList
函数中,我们遍历链表并打印节点的数据。在 main
函数中,我们创建一个空链表,然后依次插入四个节点,并最后打印整个链表。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c语言单链表程序代码怎么写
本文地址: https://pptw.com/jishu/577504.html