单链表查找第i个元素主函数代码
时间: 2023-06-01 20:02:56 浏览: 85
下面是单链表查找第i个元素的主函数代码示例:
```
#include <stdio.h>
#include <stdlib.h>
// 单链表结构体
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
// 创建单链表
ListNode* createList(int* arr, int size) {
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i = 0; i < size; i++) {
ListNode* node = (ListNode*) malloc(sizeof(ListNode));
node->val = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 查找单链表中第i个元素
ListNode* findElement(ListNode* head, int i) {
if (head == NULL || i < 1) {
return NULL;
}
ListNode* curr = head;
int count = 1;
while (curr != NULL && count < i) {
curr = curr->next;
count++;
}
if (curr == NULL) {
return NULL;
} else {
return curr;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
ListNode* head = createList(arr, size);
int i = 3;
ListNode* node = findElement(head, i);
if (node == NULL) {
printf("The %dth element does not exist.\n", i);
} else {
printf("The %dth element is %d.\n", i, node->val);
}
return 0;
}
```
在主函数中,我们创建了一个包含5个元素的单链表,并查找了第3个元素。如果查找成功,则输出该元素的值;否则输出该元素不存在。