一般思路,先遍历得到长度,再遍历得到中间的元素。
牛逼的思路是:定义两个节点,一个比另一个走的速度快一倍,那样当快的走到尾时,慢的节点正好走到了一般!!!!!!!!!!!!
一般思路的代码:()
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* result = head;(错误还是在初始化上,如果定义时未初始化,程序中也没有赋值,那么输出就是一个随机数)
int count = 0;
ListNode* current = head;
while(current)
{
current = current->next;
count++;
}
int locate = count/2 + 1;
ListNode* current1 = head;
for(int i = 0; i < locate-1; i++)
{
result = current1->next;
current1 = current1->next;
}
return result;
}
};