OJ题-给定一个带有头结点head的非空单链表,返回链表的中间结点(力扣)

题目:
在这里插入图片描述在这里插入图片描述

思路:先求出链表的长度,再除2,然后遍历链表求出中间结点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    private int getLength(ListNode head){//求出链表的长度
        int len=0;
        for(ListNode cur=head;cur!=null;cur=cur.next){//每遍历一个结点len+1
            len++;
        }
        return len;
    }
    public ListNode middleNode(ListNode head) {
        int len=getLength(head);//利用函数求出长度
        int midLen=len/2;//中间结点的位置
        ListNode node=head;
        for(int i=0;i<midLen;i++){
            node=node.next;
        }
        return node;    
    }
}

执行结果:
在这里插入图片描述
在这里插入图片描述

思路:一个走的快(fast)的引用,一个走得慢(slow)的引用,快的一次走两步,慢的一次走一步,当快的到达终点,慢的就刚好在中间。

/**
 * 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 fast=head;//快引用
        ListNode slow=head;//慢引用
        while(fast!=null){
        fast=fast.next;//快引用走的第一步
            if(fast==null){//到快引用走到尽头,跳出判断
                break;
            }
            slow=slow.next;//慢引用的步伐
            fast=fast.next;//快引用走的第二步
        }
        return slow;
    }
}

执行结果:
在这里插入图片描述

发布了61 篇原创文章 · 获赞 3 · 访问量 1210

猜你喜欢

转载自blog.csdn.net/qq_44847147/article/details/103977036