struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* GetMiddele(ListNode *head) {
if (head == nullptr)
return false;
ListNode *n1 = head;//慢指针
ListNode *n2 = head;//快指针
while (n2 != nullptr && n2->next != nullptr)//while(n2->next != nullptr && n2->next->next != nullptr){
n1 = n1->next;
n2 = n2->next->next;
}
return n1;
}
};
#include"链表插入排序.h"
#include<iostream>
using namespace std;
int main()
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode *head = &a;
head->next = &b;
head->next->next = &c;
head->next->next->next = &d;
Solution bd;
ListNode *head1 = bd.GetMiddele(head);
cout << head1->val << endl;
return 0;
}
在写查找中间节点的代码时,有两种情况,针对的是查找数的个数是偶数的情况,第一种查找的中间节点是3 第二种查找的节点是2