Leetcode-876:链表的中间节点

题目描述:

5679451-5f43c41aaa00bdf2.png

5679451-2cbf1429539227c2.png
5679451-7c139474e008cff4.png

思路:

①:遍历一遍,得到链表总长,然后再遍历到一半的位置。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        int len = 1;
        for(ListNode temp = head; temp.next!=null; temp=temp.next){
            len++;
        }
        int n = (len-1)/2;
        System.out.println(n);
        for(int i =0;i<n;i++){
            head = head.next;
        }
        //如果是偶数
        if((len&1)==0){
            return head.next;
        }else{
           return head; 
        }
        
    }
}

②:快慢指针法:快指针一次走两步,慢指针一次走一步。这样当快指针到链表末尾时(奇数个),慢指针在链表中间。如果是偶数,慢指针再向前走一步。

这个方法比较快:


5679451-e0fcfbf70b8151c4.png
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        
        ListNode fast = head;
        ListNode slow = head;
        
        while(fast.next!=null){
            
            if(fast.next.next!=null){
                fast=fast.next.next;
                slow = slow.next;
            }else{
                fast= fast.next;
                slow=slow.next;
            }
            
        }
        return slow;        
    }
}

转载于:https://www.jianshu.com/p/f738503d8f04

猜你喜欢

转载自blog.csdn.net/weixin_34146986/article/details/91186461