单链表按位置查找并返回找到的值,用c语言实现
时间: 2023-05-30 14:06:45 浏览: 99
以下是用C语言实现单链表按位置查找并返回找到的值的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结点结构体
struct Node {
int data;
struct Node* next;
};
// 定义单链表查找函数
int findNode(struct Node* head, int pos) {
struct Node* p = head;
int count = 1;
// 遍历链表,查找对应位置的结点
while (p != NULL && count < pos) {
p = p->next;
count++;
}
// 如果找到了对应位置的结点,返回该结点的值
if (p != NULL) {
return p->data;
}
// 如果没找到对应位置的结点,返回-1
return -1;
}
int main() {
// 创建单链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
head->data = 0;
node1->data = 1;
node2->data = 2;
node3->data = 3;
head->next = node1;
node1->next = node2;
node2->next = node3;
node3->next = NULL;
// 按位置查找结点
int pos = 2;
int value = findNode(head, pos);
if (value != -1) {
printf("找到了第%d个结点,值为%d\n", pos, value);
} else {
printf("没有找到第%d个结点\n", pos);
}
// 释放内存
free(head);
free(node1);
free(node2);
free(node3);
return 0;
}
```
输出结果为:
```
找到了第2个结点,值为1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)