Leetcode-876 链表的中间结点

Leetcode-876 链表的中间结点_第1张图片
Leetcode-876 链表的中间结点_第2张图片
本人解法有点硬凑答案…

/**
 * 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;
    }
}

你可能感兴趣的:(Leetcode刷题,leetcode,链表,算法,java,数据结构)