LeetCode876 Middle of the Linked List

题目原意是找一个链表的中间结点,如果中间结点有两个,取靠后的那个

沙雕解法

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

给定的是结点数据结构是这样的,因此不能直接用Java里的ArrayList.get(list.size() / 2)这样的方法,我想到的方法就是先遍历一次链表,得到长度,得到中间结点的位置,再迭代,得到中间结点。

public ListNode middleNode(ListNode head) {
    if (head == null) {
        return null;
    }
    ListNode tmpListNode = head;
    int index = 0, middle;
    while (tmpListNode != null) {
        index += 1;
        tmpListNode = tmpListNode.next;
    }
    if (index % 2 == 0) {
        middle = (int) Math.floor(index / 2);
    } else {
        middle = index / 2;
    }
    while (middle > 0) {
        head = head.next;
        middle--;
    }
    return head;
}

快慢指针法

先看代码

public ListNode middleNodeTwoPoint(ListNode head) {
    if (head == null) {
        return null;
    }
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

slow指针每次往后动一个结点,fast每次往后动两个结点,因此fast走到链表的的末尾时,slow刚好走到链表的中间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值