链表问题的最优解在 空间复杂度上,也就是在笔试阶段可以利用辅助空间加速计算
剑指06- 从尾到头打印链表
public class _06_从尾到头打印链表 {
// 链表的题,主要是在空间复杂度上优化
// 利用额外数据结构进行求解
// 反转的东西,优先考虑栈和队列
public int[] reversePrint(ListNode head) {
Stack<Integer> stackData = new Stack<>();
ListNode cur = head;
while (cur != null) {
stackData.push(cur.val);
cur = cur.next;
}
int[] res = new int[stackData.size()];
for (int i = 0; i < res.length; i++) {
res[i] = stackData.pop();
}
return res;
}
}
剑指18- 删除链表的节点
public class _18_删除链表中的节点 {
public ListNode deleteNode(ListNode head, int val) {
ListNode headFake = new ListNode(0);
headFake.next = head;
ListNode cur = headFake;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
break;
}
cur = cur.next;
}
return headFake.next;
}
}
剑指22-链表中倒数第k个节点
public class _22_链表中倒数第k个节点 {
// 快慢指针,这种倒数的问题
public ListNode getKthFromEnd(ListNode head, int k) {
// 边界问题
if (head == null || k <= 0) return null;
ListNode headFake = new ListNode(0);
headFake.next = head;
ListNode slow = headFake;
ListNode fast = headFake;
for (int i = 0; i < k; i++) {
// k如果大于总节点数:属于边界判断
if (fast != null) {
fast = fast.next;
} else {
return null;
}
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
剑指24- 反转链表
public class _24_反转链表 {
// 递归思想
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode reverse = reverseList(head.next);
head.next.next = head;
head.next = null;
return reverse;
}
}
剑指35-复杂链表的复制
public class _35_复杂链表的复制 {
public Node copyRandomList(Node head) {
if(head == null) return null;
Node cur = head;
// 1. 复制各节点,并构建拼接链表
while(cur != null) {
Node tmp = new Node(cur.val);
tmp.next = cur.next;
cur.next = tmp;
cur = tmp.next;
}
// 2. 构建各新节点的 random 指向
cur = head;
while(cur != null) {
if(cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
// 3. 拆分两链表
cur = head.next;
Node pre = head, res = head.next;
while(cur.next != null) {
pre.next = pre.next.next;
cur.next = cur.next.next;
pre = pre.next;
cur = cur.next;
}
pre.next = null; // 单独处理原链表尾节点
return res; // 返回新链表头节点
}
}
剑指52-两个链表的第一个公共节点
public class _52_两个链表的第一个公共节点 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pA = headA;
ListNode pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}