Middle of Linked List
Find the middle node of a linked list.
Example
Given 1->2->3, return the node with value 2.
Given 1->2, return the node with value 1.
法①(Java)快慢指针
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/*
* @param head: the head of linked list.
* @return: a middle node of the linked list
*/
public ListNode middleNode(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){//×:slow != null
//快指针步长为2 ,慢指针步长为1。 当快指针走到头,慢指针恰好到中点。
//故:循环终止条件应该为 快指针的下个/下下个结点为null
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
(2)法②(C++版)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution{
public:
/**
* @param head: the head of linked list.
* @return: a middle node of the linked list
*/
ListNode *middleNode(ListNode *head) {
if (head == NULL)
return NULL;
int cnt = 0;
ListNode *p = head;
while (p != NULL) {
cnt ++;
p = p->next;
}
cnt = (cnt + 1) / 2;
while (head != NULL) {
if (cnt == 1)
return head;
cnt --;
head = head->next;
}
}
};