单链表的按位查找完整代码
时间: 2024-06-16 11:06:10 浏览: 12
单链表的按位查找是指根据给定的位置,查找链表中对应位置的节点。以下是单链表按位查找的完整代码示例:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构
struct ListNode {
int data; // 节点数据
ListNode* next; // 指向下一个节点的指针
};
// 按位查找链表节点
ListNode* findNodeByPosition(ListNode* head, int position) {
if (head == nullptr || position <= 0) {
return nullptr;
}
ListNode* current = head;
int count = 1;
while (current != nullptr && count < position) {
current = current->next;
count++;
}
return current;
}
// 创建链表
ListNode* createLinkedList(int n) {
if (n <= 0) {
return nullptr;
}
ListNode* head = nullptr;
ListNode* tail = nullptr;
for (int i = 1; i <= n; i++) {
ListNode* newNode = new ListNode();
newNode->data = i;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 打印链表
void printLinkedList(ListNode* head) {
ListNode* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main() {
int n; // 链表长度
int pos; // 查找位置
cout << "请输入链表长度:";
cin >> n;
ListNode* head = createLinkedList(n);
cout << "请输入要查找的位置:";
cin >> pos;
ListNode* result = findNodeByPosition(head, pos);
if (result != nullptr) {
cout << "查找结果为:" << result->data << endl;
} else {
cout << "查找失败,位置超出链表长度!" << endl;
}
return 0;
}
```
相关推荐
![](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)
![](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)