力扣876.链表的中间节点

876.链表的中间节点

思路1(数组):
  1. 新建 ListNode 数组存放 节点
  2. 根据节点个数 t ,返回 ListNode 的 t/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) {
        ListNode[] A = new ListNode[100];
        int t = 0;
        while (head!= null) {
            A[t++] = head;
            head = head.next;
        }

        return A[t/2];
    }
}
思路2(单指针法):
  1. 先通过循环一边链表,得出节点个数
  2. 根据节点个数 除以 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 n = 0;
        ListNode cur = head;
        while (cur != null) {
            n++;
            cur = cur.next;
        }

        cur = head;
        int k = 0;
        while (k < (n/2)) {
            k++;
            cur = cur.next;
        }
        return cur;
    }
}
思路3(快慢指针):

只要从同一时间同一地点出发,当快指针走到末尾时,慢指针一定走到中间

  1. 创建 快慢指针 同时指向 head
  2. 使用while循环,slow走一步,fast走两步,找判断条件
  3. 返回 slow
注意:

while (fast != null && fast.next != null ) 条件顺序一定不能反,否则会导致越界

代码实现
/**
 * 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;
        ListNode fast = head;

        while (fast != null && fast.next != null ) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

你可能感兴趣的:(链表,leetcode,数据结构)