228. 鏈表的中點
找鏈表的中點。
樣例
樣例 1:
輸入: 1->2->3
輸出: 2
樣例解釋: 返回中間節點的值
樣例 2:
輸入: 1->2
輸出: 1
樣例解釋: 如果長度是偶數,則返回中間偏左的節點的值。
代碼區:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* username:softstarhhy
* @param head: the head of linked list.
* @return: a middle node of the linked list
*/
public ListNode middleNode(ListNode head) {
// write your code here
if(head==null)
{
return head;
}
if(head!=null&&head.next==null)
{
return head;
}
ListNode p=head;
ListNode q=p.next;
ListNode h1=head;
ListNode h2=head;
int nums=1;
int cur=1;
if(head==null)
{
return head;
}
while(p!=null)
{
if(q.next!=null)
{
nums++;
p=q;
q=q.next;
}else
{
nums++;
p=q;
q=q.next;
break;
}
}
if(nums%2==0)
{
while(h1!=null)
{
if((cur==1)&&(nums==2))
{
q=h1;
break;
}
h1=h1.next;
cur++;
if(cur==(nums/2))
{
q=h1;
}
}
}
else
{
while(h2!=null)
{
h2=h2.next;
cur++;
if(cur==(nums/2)+1)
{
q=h2;
}
}
}
return q;
}
}