查找链表的中间节点,只能遍历一次数组
方法及思想
因为要求只能遍历一次链表,那么我们就可以边遍历边查找中间的节点。每遍历一步,就找一次中间节点,然后移动只想中间节点的指针。此处借助链表的长度来实现这个解法,我假设在链表长度为偶数时,中间节点为length/2取下取整(参考二分法)
代码
#include<iostream>
using namespace std;
struct list {
int val;
list* next;
list(int x) :val(x), next(nullptr){}
};
尾插创建链表
list* insert(list* head,int x) {
list* p = head;
while (p->next)
{
p = p->next;
}
list* t = new list(x);
p->next = t;
return head;
}
从头打印链表
void pprint(list* head) {
if (nullptr == head) {
return;
}
else {
if (nullptr == head->next)cout << head->val << endl;
else cout << head->val << "->";
}
return pprint(head->next);
}
查找链表的中间节点,只能遍历一次链表
list* Find(list* head) {
if (nullptr == head) return nullptr;
int length = 1;
int mid = 1;
int now = 1;
list* ans = head;
list* p = head;
while (p->next) {
p = p->next;
length++;
if (0 == length % 2) {
mid = length / 2;
}
else {
mid = length / 2 + 1;
}
for (int i = now; i < mid; i++) {
ans = ans->next;
}
now = mid;
}
return ans;
}
int main() {
list* head = new list(0);
for (int i = 1; i < 11; i++) {
insert(head, i);
}
pprint(head);
list* mid=Find(head);
cout << mid->val;
return 0;
}