用C语言写链表的显示链表操作
时间: 2023-09-30 11:10:03 浏览: 95
以下是用C语言实现链表显示的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 创建新节点
ListNode* createNode(int val) {
ListNode *node = (ListNode*) malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 添加节点到链表末尾
ListNode* addNode(ListNode *head, int val) {
if (head == NULL) {
head = createNode(val);
} else {
ListNode *cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = createNode(val);
}
return head;
}
// 显示链表
void showList(ListNode *head) {
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
ListNode *head = NULL;
head = addNode(head, 1);
head = addNode(head, 2);
head = addNode(head, 3);
showList(head);
return 0;
}
```
运行结果:
```
1 2 3
```
阅读全文