一、什么是链表(Linked List)
之前的动态数组、栈、队列的底层依托静态数组,靠resize解决固定容量问题
- 1、正的一种最简单的动态数据结构
- 2、更深入的理解引用(或者指针)
- 3、更深入的理解递归
- 4、辅助组成其他数据结构
- 5、数据存储在节点(Node)中
class Node { E e; Node next; }
- a、优点:真正的动态,不需要处理固定容量的问题
- b、缺点:丧失了随机访问的能力
二、在链表中添加元素
- 1、在链表头部添加元素
// head表示头部第一个元素,新元素node
Node node = new Node(e)
node.next = head
head = node
// 另外一种写法
head = new Node(e, head)
-
2、在链表中间添加元素
- a、先找到prev
Node prev = head; for(int i = 0; i < index -1; i++) { prev = prev.next; }
- b、插入元素
// 插入第一种写法 Node node = new Node(e); node.next = prev.next; prev.next = node; // 另外一种写法 prev.next = new Node(e, prev.next)
- a、先找到prev
-
3、为链表设立虚拟头结点
三、链表的遍历、查询和修改
四、链表的删除
五、递归
本质上,将原来的问题,转换成更小的同一问题
数组求和
public class Sum{
public static int sum(int[] arr){
return sum(arr, 0);
}
// 计算arr[l...n)这个区间诶所有数字的和,0 -> arr.length - 1 数字的和
private static int sum(int [] arr, int l) { // l为左边界
if(l == arr.length)
return 0;
return arr[l] + sum(arr, l+1);
}
}
递归的微观解读
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return null;
ListNode res = removeElements(head.next,val);
if(head.val == val)
return res;
else {
head.next = res;
return head;
}
}
}