定义main函数验证单链表
时间: 2023-08-24 07:05:22 浏览: 58
好的,下面是一个简单的例子,用来验证刚才定义的单链表:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建新节点
struct ListNode* createNode(int val) {
struct ListNode *newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
// 插入新节点
void insertNode(struct ListNode** head, struct ListNode* node) {
if (*head == NULL) {
*head = node;
return;
}
struct ListNode *cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
// 打印链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
}
int main() {
// 创建链表
struct ListNode *head = NULL;
insertNode(&head, createNode(1));
insertNode(&head, createNode(2));
insertNode(&head, createNode(3));
insertNode(&head, createNode(4));
insertNode(&head, createNode(5));
// 打印链表
printList(head);
return 0;
}
```
在这个例子中,我们创建了一个包含五个节点的单链表,并打印整个链表。你可以通过编译并运行该程序,验证单链表的正确性。