学习目标:
算法总结一: Linked List
学习内容:
1、 Leetcode题库Linked List tag高频题学习时间:
1、 周一至周天晚上 7 点—晚上9点学习产出:
1、 技术笔记 1 篇2、解题思路视频1个
=====================================
linked list的特性包含:无法直接获取一个list的size,无法random access。一些基本操作如:
reverse,
findMid,
reorder,
sort,
remove,
merge,
partition
易错点较多。以下为学习总结:
1.Reverse
206. Reverse Linked List
recursion的解法:
好奇:子问题中如果当前head是2,那么head.next=null会执行吗?
解答:跑idea时会的,每一步都会执行
nxt.next=head;
head.next=null;
但由于是从尾巴开始递归/back track的,
所以前一步的head.next=null都会被改写,
最后一步是null才定局,最终接地。
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null){
return head;
}
//1-> [2->3->4->5->NULL]
//head nxt
ListNode nxt=head.next;
ListNode newHead=reverseList(head.next);
//子问题是head.next
//这里也相当于head=head.next往下走。
nxt.next=head;
head.next=null;
return newHead;
}
}
iteration的解法:
class Solution {
public ListNode reverseList(ListNode head) {
// 1----2----3----null
//prev cur nxt
// prev cur
ListNode prev=null;
ListNode cur=head;
while(cur!=null){
ListNode nxt=cur.next;
cur.next=prev;//反指针
prev=cur; //走一步
cur=nxt; //走一步
}
return prev;
}
}
25. Reverse Nodes in k-Group
recursion的解法:
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1) return head;
//1.count k,ex: k=3
int count=0;
ListNode cur=head;
while(count<k && cur!=null){
//count==3跳出
cur=cur.next;
count++;
}
if(count==k){
ListNode reversedHead = reverseLL(head,k);
//2.reverse k nodes
//3.recursively solve this problem: .next=reverseKGroup(head+k, k)
head.next=reverseKGroup(cur, k);
//1.next=reverseKGroup(4,3); 指向新头,所以这里总的要返回新头
return reversedHead;
}
//否则,无法做count和reverse,就:
return head;
}
public ListNode reverseLL(ListNode head,int k){
ListNode prev=null;
ListNode cur=head;
while(k>0){
ListNode nxt=cur.next;
cur.next=prev;//null<--1 改变指向,
prev=cur;//prev指针往右边走
cur=nxt;//cur指针往右边走,
k--;
}
return prev;
}
}
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == 1) {
// You can also expand the code here to get rid of the helper function 'reverseN'
return reverseN(head, n);
}
head.next = reverseBetween(head.next, m - 1, n - 1);
return head;
}
ListNode successor = null;
ListNode reverseN(ListNode head, int n) {
if (n == 1) {
successor = head.next;
return head;
}
ListNode last = reverseN(head.next, n