单链表查找第i个元素全部代码
时间: 2023-06-01 21:02:55 浏览: 125
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* findNode(ListNode* head, int i) {
if (head == nullptr) return nullptr; // 如果链表为空,返回 nullptr
ListNode* cur = head;
int count = 1;
while (cur != nullptr && count != i) {
cur = cur->next;
count++;
}
return cur; // 返回第 i 个节点,如果 i 超出了链表长度,返回 nullptr
}
相关问题
单链表查找第i个元素Java代码
在Java中,单链表查找第i个元素通常涉及到遍历整个链表。这里是一个简单的示例,假设我们有一个`Node`类表示链表节点:
```java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
private Node head;
// 添加元素到链表的头部
public void add(int value) {
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
}
// 查找第i个元素
public Node findElement(int i) {
if (head == null || i < 0) {
return null; // 如果链表为空或索引越界,则返回null
}
Node current = head;
for (int index = 1; index <= i; index++) { // 遍历i次
if (current == null) {
return null; // 如果还没找到元素并且当前节点为空,说明不存在该位置
}
current = current.next; // 移动到下一个节点
}
return current; // 返回第i个节点
}
}
```
在这个例子中,如果你想要查找链表的第i个元素,可以创建一个`LinkedList`对象并调用`findElement(i)`方法。如果链表长度小于i,或者索引i无效,函数将返回`null`。
单链表查找第i个元素主函数代码
下面是单链表查找第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个元素。如果查找成功,则输出该元素的值;否则输出该元素不存在。
阅读全文
相关推荐













