本人解法有点硬凑答案…
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
int len=0;
ListNode p=head;
while(p!=null){
len++;
p=p.next;
}
if(len==1){
return head;
}
int i=0;
while(i<len/2-1){
i++;
head=head.next;
}
return head.next;
}
}
学习一下优秀解法:
快慢指针,快指针走两个节点,慢指针走一个结点(妙哉!!!!)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
}