《演算法筆記二》連結串列、棧、佇列、遞迴、雜湊表、順序表
阿新 • • 發佈:2020-07-13
[TOC]
# 連結串列、棧、佇列、遞迴、雜湊
## 連結串列
### 單向連結串列
> 單向連結串列的節點結構(可以實現成泛型) :
```Java
public class Node {
public int value;
public Node next;
public Node(int data) {
value = data;
}
}
```
### 雙向連結串列
> 雙向連結串列的節點結構(可以實現成功泛型):
```Java
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
value = data;
}
}
```
### 單雙鏈表簡單練習
1. 單鏈表和雙鏈表如何反轉
> 1 -> 2 -> 3 轉換為 3 -> 2 -> 1
```Java
package class02;
import java.util.ArrayList;
public class Code01_ReverseList {
public static class Node {
public int value;
public Node next;
public Node(int data) {
value = data;
}
}
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
value = data;
}
}
// 翻轉單向連結串列,傳入頭結點
public static Node reverseLinkedList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
// 翻轉雙向連結串列,傳入頭結點
public static DoubleNode reverseDoubleList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
public static Node testReverseLinkedList(Node head) {
if (head == null) {
return null;
}
A