《演算法筆記》6. 連結串列相關面試題總結
阿新 • • 發佈:2020-07-21
[TOC]
# 1 連結串列問題
> 面試時連結串列解題的方法論
> 對於筆試,不用太在乎空間複雜度,一切為了時間複雜度
> 對於面試,時間複雜度依然放在第一位,但是一定要找到空間最省的方法
## 1.1 連結串列面試常用資料結構和技巧
1、 使用容器(雜湊表,陣列等)
2、 快慢指標
### 1.1.1 快慢指標問題
1、 輸入連結串列頭結點,奇數長度返回中點,偶數長度返回上中點
> 1 3 5 2 7 返回 5;1 3 2 7 返回 3
2、 輸入連結串列頭結點,奇數長度返回中點,偶數長度返回中下點
> 1 3 5 2 7 返回 5;1 3 2 7 返回 2
3、 輸入連結串列頭結點,奇數長度返回中點前一個,偶數長度返回上中點前一個
> 1 3 5 2 7 返回 3;1 3 2 7 返回 1
4、 輸入連結串列頭結點,奇數長度返回中點前一個,偶數長度返回下中點前一個
> 1 3 5 2 7 返回 3;1 3 2 7 返回 3
```Java
package class06;
import java.util.ArrayList;
public class Code01_LinkedListMid {
public static class Node {
public int value;
public Node next;
public Node(int v) {
value = v;
}
}
// head 頭
// 1、奇數長度返回中點,偶數長度返回上中點
public static Node midOrUpMidNode(Node head) {
// 沒有點,有一個點,有兩個點的時候都是返回頭結點
if (head == null || head.next == null || head.next.next == null) {
return head;
}
// 連結串列有3個點或以上
// 快慢指標,快指標一次走兩步,慢指標一次走一步
// 快指標走完,慢指標在中點位置
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;
}
// 4、奇數長度返回中點前一個,偶數長度返回下中點前一個
public static Node midOrDownMidPreNode(Node head) {
if (head == null || head.next == null) {
return null;
}
if (head.next.next == null) {
return head;
}
Node slow = head;
Node fast = head.next;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// 筆試可以用這種複雜點的方法,空間複雜度比上面快慢指標要高
public static Node right1(Node head) {
if (head == null) {
return null;
}
Node cur = head;
A