带有头结点的单链表按序号查找c语言
时间: 2023-05-10 10:55:27 浏览: 58
可以使用循环遍历单链表,根据节点的序号逐个比较,直到找到目标节点或者遍历完整个链表。以下是一个示例代码:
```
typedef struct ListNode {
int data;
struct ListNode* next;
} ListNode;
ListNode* findNodeByIndex(ListNode* head, int index) {
ListNode* p = head->next;
int i = 1;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (i == index && p != NULL) {
return p;
} else {
return NULL;
}
}
```
这个函数接受一个带有头结点的单链表的头指针和一个节点序号,返回对应的节点指针。如果找不到对应的节点,返回 NULL。
相关问题
单链表按序号查找结点值c语言
实现代码如下:
```
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList(int arr[], int n) {
struct ListNode* head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = arr[i];
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int searchNode(struct ListNode* head, int pos) {
struct ListNode* p = head;
int cnt = 0;
while (p != NULL && cnt < pos) {
cnt++;
p = p->next;
}
if (p == NULL) {
return -1;
} else {
return p->val;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
struct ListNode* head = createList(arr, n);
int pos = 3;
int val = searchNode(head, pos);
if (val == -1) {
printf("不存在这个节点\n");
} else {
printf("第%d个节点的值为%d\n", pos, val);
}
return 0;
}
```
这是一个基于C语言的单链表结构实现,其中createList函数用于创建一个单链表,searchNode函数用于按序号查找链表中的节点值。
编写算法,实现在带有头结点的单链表中按序号查找的函数。
以下是实现在带有头结点的单链表中按序号查找的函数的算法:
```
Node* findNodeByIndex(LinkedList* list, int index) {
if (list == NULL || index < 0) {
return NULL;
}
Node* p = list->head;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
return p;
}
```
其中,LinkedList 是一个结构体,表示单链表,包含一个头结点和一个尾结点。Node 是一个结构体,表示链表中的一个节点,包含一个指向下一个节点的指针和一个数据域。