面試時鏈表解題方法論
(1)對於筆試,不用太在乎空間複雜度,一切爲了時間複雜度
(2)對於面試,時間複雜度依然放第一位,但是一定要找到最省空間的辦法
面試題:快慢指針
(1)輸入鏈表頭結點,奇數長度返回中點,偶數長度返回上中點(中點左邊的值)
(2)輸入鏈表頭結點,奇數長度返回中點,偶數長度返回下中點
(3)輸入鏈表頭結點,奇數長度返回中點前一個,偶數長度返回中點前一個
package com.inspire.chapter6;
public class Code01_LinkedListMid {
public static class Node {
public int value;
public Node next;
public Node(int v) {
value = v;
}
}
// (1)輸入鏈表頭結點,奇數長度返回中點,偶數長度返回上中點(中點左邊的值)
public static Node midOrUpMidNode(Node head) {
if (head == null || head.next == null || head.next.next == null) {
return head;
}
// 三個或以上的單鏈表執行下面這個
Node slow = head.next;
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;// 快指針一次走兩步,當快指針到終點的時候,慢指針就走到上中點了
}
return slow;
}
// (2)輸入鏈表頭結點,奇數長度返回中點,偶數長度返回下中點
public static Node midOrDownMidNode(Node head) {
if (head == null || head.next == null) {// 如果頭結點爲空或只有一個結點,返回第一個幾點就行
return head;
}
// 兩個或以上的單鏈表執行下面這個
Node slow = head.next;
Node fast = head.next;// 只需要快指針在上一個方法裏退一步就可以了
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// (3)輸入鏈表頭結點,奇數長度返回中點前一個,偶數長度返回中點前一個
public static Node midOrUpMidPreNode(Node head) {
if (head == null || head.next == null || head.next.next == null) {// 節點數爲兩個及以下的單鏈表返回空
return null;
}
Node slow = head;// 慢指針再慢一步就可以了
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static void main(String[] args) {
Node test = null;
test = new Node(1);
test.next = new Node(2);
test.next.next = new Node(3);
test.next.next.next = new Node(4);
test.next.next.next.next = new Node(5);
test.next.next.next.next.next = new Node(6);
// test.next.next.next.next.next.next = new Node(7);
// test.next.next.next.next.next.next.next = new Node(8);
// test.next.next.next.next.next.next.next.next = new Node(9);
System.out.println(midOrUpMidNode(test).value);
System.out.println(midOrDownMidNode(test).value);
System.out.println(midOrUpMidPreNode(test).value);
}
}