1. 力扣876 : 鏈表的中間節點
(1). 題
給你單鏈表的頭結點?head
?,請你找出并返回鏈表的中間結點。
如果有兩個中間結點,則返回第二個中間結點。
示例 1:
?
輸入:head = [1,2,3,4,5] 輸出:[3,4,5] 解釋:鏈表只有一個中間結點,值為 3 。
示例 2:
?
輸入:head = [1,2,3,4,5,6] 輸出:[4,5,6] 解釋:該鏈表有兩個中間結點,值分別為 3 和 4 ,返回第二個結點。
提示:
- 鏈表的結點數范圍是?
[1, 100]
1 <= Node.val <= 100
(2). 思路 : 輔助數組
我發現鏈表的很多題目,尤其是簡單題,大部分都可以用輔助數組來解決,讓鏈表問題直接轉化為數組問題.?
(3). 解
/*** 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) {if (head == null) {return head;}ListNode p = head;int count = 0;while (p != null) {count++;p = p.next;}int[] arr = new int[count];p = head;for (int i = 0; i < count; i++) {arr[i] = p.val;p = p.next;}p = head;for (int i = 0; i < count/2; i++) {p = p.next;}return p;}
}
(4). 思路2 : 快慢指針
依據快慢指針,快指針一次走兩步,慢指針一次走一步.
(5). 解2
class Solution {public ListNode middleNode(ListNode head) {if(head == null) {return null;}ListNode fast = head;ListNode slow = head;while (fast.next != null && fast.next.next != null) {fast = fast.next.next;slow = slow.next;}return fast.next == null ? slow : slow.next;}
}