• 【零基础算法】链表算法


     

    链表算法

    这次带来的是有关于链表题的相应训练,对应的数据结构较为基础,大家可以自行去了解,或者等后面博主有空复习时重新写一篇博客,今天就暂时直接开始算法吧!

    这次将围绕以下几个方面来进行链表算法的练习:

    1. 合并两个有序链表

    2. 链表的分解

    3. 合并k个有序链表

    4. 寻找单链表的倒数第k个节点

    5. 寻找单链表的中点

    6. 判断单链表是否包含环并找出环七点

    7. 判断两个单链表是否相交并找出交点

    这些操作基本上都使用到了双链表的算法

    合并两个有序链表

    21. 合并两个有序链表 - 力扣(LeetCode)

    1. class Solution {
    2.    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
    3.        ListNode ans = null;
    4.        ListNode tmp = null;
    5.        while(list1!=null || list2!=null) {
    6.            int tmp1 = list1 == null ? 101:list1.val;
    7.            int tmp2 = list2 == null ? 101:list2.val;
    8.            int tmp3;
    9.            if(tmp1 < tmp2) {
    10.                list1 = list1.next;
    11.                tmp3 = tmp1;
    12.           } else {
    13.                list2 = list2.next;
    14.                tmp3 = tmp2;
    15.           }
    16.            ListNode newNode = new ListNode();
    17.            newNode.val = tmp3;
    18.            if(tmp == null) {
    19.                ans = tmp = newNode;
    20.           } else {
    21.                tmp.next = newNode;
    22.                tmp = newNode;
    23.                tmp.next = null;
    24.           }
    25.       }
    26.        return ans;
    27.   }
    28. }

    当你需要创造一条新链表的时候,可以使用虚拟头(dummy)结点简化边界情况的处理

    单链表的分解

    86. 分隔链表 - 力扣(LeetCode)

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. *     int val;
    5. *     ListNode next;
    6. *     ListNode() {}
    7. *     ListNode(int val) { this.val = val; }
    8. *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12.    public ListNode partition(ListNode head, int x) {
    13.        ListNode dummy1 = new ListNode(-1),p1=dummy1;
    14.        ListNode dummy2 = new ListNode(-1),p2=dummy2;
    15.        ListNode p3 = head;
    16.        while(p3!=null) {
    17.            if(p3.val < x) {
    18.                ListNode newNode = new ListNode(p3.val);
    19.                p1.next = newNode;
    20.                p1 = newNode;
    21.           } else {
    22.                ListNode newNode = new ListNode(p3.val);
    23.                p2.next = newNode;
    24.                p2 = newNode;
    25.           }
    26.            p3 = p3.next;
    27.       }
    28.        p1.next = dummy2.next;
    29.        p2.next = null;
    30.        return dummy1.next;
    31.   }
    32. }
    1. class Solution {
    2. // public boolean isPalindrome(ListNode head) {
    3. // ListNode head2 = new ListNode(head.val);
    4. // ListNode p = head.next;
    5. // ListNode p2 = head2;
    6. // while(p!=null) {
    7. // ListNode newNode = new ListNode(p.val);
    8. // p2.next = newNode;
    9. // p2 = newNode;
    10. // p=p.next;
    11. // }
    12. // head2 = reverse(head2);
    13. // while(head2!=null) {
    14. // if(head2.val!=head.val) return false;
    15. // head = head.next;
    16. // head2 = head2.next;
    17. // }
    18. // return true;
    19. // }
    20. // public ListNode reverse(ListNode head) {
    21. // if(head == null || head.next == null) {
    22. // return head;
    23. // }
    24. // ListNode last = reverse(head.next);
    25. // head.next.next = head;
    26. // head.next = null;
    27. // return last;
    28. // }
    29. private ListNode left;
    30. public boolean isPalindrome(ListNode head) {
    31. left = head;
    32. return trease(head);
    33. }
    34. public boolean trease(ListNode head){
    35. if(head == null) return true;
    36. boolean res = trease(head.next);
    37. res = res && (left.val == head.val);
    38. left = left.next;
    39. return res;
    40. }
    41. }

    这里可以把原链表的节点断开,也可以new新节点。

    23. 合并 K 个升序链表 - 力扣(LeetCode)

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. *     int val;
    5. *     ListNode next;
    6. *     ListNode() {}
    7. *     ListNode(int val) { this.val = val; }
    8. *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12.    public ListNode mergeKLists(ListNode[] lists) {
    13.        int len = lists.length;
    14.        //System.out.println(len);
    15.        ListNode dummy = new ListNode(-1),p = dummy;
    16.        int[] nums = new int[len];
    17.        int index = 0;
    18.        int min = 0;
    19.        while(true) {
    20.            int count = 0;
    21.            min = 100000;
    22.            for(int i = 0 ; i < len ; i++) {
    23.                nums[i] = lists[i] == null ? 100000:lists[i].val;
    24.                if(nums[i] < min) {
    25.                    min = nums[i];
    26.                    index = i;
    27.               }
    28.                if(lists[i] == null) count++;
    29.           }
    30.            if(count == len) break;
    31.            p.next = lists[index];
    32.            p = lists[index];
    33.            ListNode tmp = lists[index].next;
    34.            lists[index].next = null;
    35.            lists[index] = tmp;
    36.       }
    37.        return dummy.next;
    38.   }
    39. }

    这里的解法使用最原始的暴力解法,多指针的方法,一次取一个最小数,直到最后所有指针全为空。

    升级的用法就使用优先队列(二叉堆)这种数据结构。

    1. ListNode mergeKLists(ListNode[] lists) {
    2.    if (lists.length == 0) return null;
    3.    // 虚拟头结点
    4.    ListNode dummy = new ListNode(-1);
    5.    ListNode p = dummy;
    6.    // 优先级队列,最小堆
    7.    PriorityQueue pq = new PriorityQueue<>(
    8.        lists.length, (a, b)->(a.val - b.val));
    9.    // 将 k 个链表的头结点加入最小堆
    10.    for (ListNode head : lists) {
    11.        if (head != null)
    12.            pq.add(head);
    13.   }
    14.    while (!pq.isEmpty()) {
    15.        // 获取最小节点,接到结果链表中
    16.        ListNode node = pq.poll();
    17.        p.next = node;
    18.        if (node.next != null) {
    19.            pq.add(node.next);
    20.       }
    21.        // p 指针不断前进
    22.        p = p.next;
    23.   }
    24.    return dummy.next;
    25. }

    单链表的倒数第k个节点

    普通解法:

    1. 遍历一遍链表,得出链表的长度n

    2. 再遍历一遍链表,并记录长度,到达n-k+1的时候就是结果

    这样需要遍历两边链表

    双指针:

    1. 先用一个指针,走k步。

    2. 用另一个指针指向头节点,之后两个指针一起走,第一个指针走到尽头的时候,第二个指针就是倒数第k个位置。

    19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. *     int val;
    5. *     ListNode next;
    6. *     ListNode() {}
    7. *     ListNode(int val) { this.val = val; }
    8. *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12.    public ListNode removeNthFromEnd(ListNode head, int n) {
    13.        ListNode p1 = head;
    14.        ListNode p2 = head;
    15.        ListNode dummy = new ListNode(-1);
    16.        dummy.next = head;
    17.        ListNode pre = dummy;
    18.        for(int i = 0 ; i < n ; i++) {
    19.            p1 = p1.next;
    20.       }
    21.        while(p1!=null) {
    22.            p1=p1.next;
    23.            p2=p2.next;
    24.            pre = pre.next;
    25.       }
    26.        pre.next = p2.next;
    27.        return dummy.next;
    28.   }
    29. }

    单链表的中点&判断链表是否有环

    中点问题&判断链表是否有环可以使用快慢指针法:

    一个指针为fast,一个指针为slow,fast一次前进两步,而slow一次前进一步,那么,当fast到末尾的时候,slow就是表的中点。

    需要注意的是,如果链表长度为偶数,也就是说中点有两个的时候,我们这个解法返回的节点是靠后的那个节点。

    但如果在链表中,有一次slow追上了fast指针,也就是slow == fast的时候,就说明链表有环

    876. 链表的中间结点 - 力扣(LeetCode)

    1. class Solution {
    2.    public ListNode middleNode(ListNode head) {
    3.        ListNode fast = head;
    4.        ListNode slow = head;
    5.        while(true) {
    6.            fast = fast.next;
    7.            if(fast == null) break;
    8.            slow = slow.next;
    9.            fast = fast.next;
    10.            if(fast == null) break;
    11.       }
    12.        return slow;
    13.   }
    14. }

    142. 环形链表 II - 力扣(LeetCode)

    1. public class Solution {
    2.    public ListNode detectCycle(ListNode head) {
    3.        if(head == null) return null;
    4.        ListNode slow = head;
    5.        ListNode fast = head;
    6.        while(true) {
    7.            fast = fast.next;
    8.            if(fast == null) return null;
    9.            slow = slow.next;
    10.            fast = fast.next;
    11.            if(fast == null) return null;
    12.            if(fast == slow) break;
    13.       }
    14.        slow = head;
    15.        while(slow!=fast) {
    16.            fast = fast.next;
    17.            slow = slow.next;
    18.       }
    19.        return slow;
    20.   }  
    21. }

    寻找环的入口:快慢指针相遇之后,假设慢指针走了k步,那么快指针走了2k步(因为快指针比满指针快1步)。假设相遇点距离环入口m步,那么实际上满指针走了k-m步(环外),m步(环内)。而快指针了2k步,和慢指针一样,k-m步时环外的,剩下的k+m步是在环内走的,但是环内肯定是有循环的,那么在m处相遇的情况下,快指针入环走m步后,循环了一圈又到m与慢指针相遇,k+m-m=k。所以也就是说,快指针在环内从m处的地方走了k步,又与慢指针相遇。那扣去一开始的相遇点的m步,剩下走k-m就是入口了。所以当快慢指针相遇时,一个指针从头开始走,快指针一次走一步,两个指针相遇时就是入口。

    两个链表是否相交

    如果用两个指针 p1p2 分别在两条链表上前进,并不能同时走到公共节点,也就无法得到相交节点 c1

    解决这个问题的关键是,通过某些方式,让 p1p2 能够同时到达相交节点 c1

    可以相当于遍历两个链表,让两个链表变成相同长度。可以让 p1 遍历完链表 A 之后开始遍历链表 B,让 p2 遍历完链表 B 之后开始遍历链表 A,这样相当于「逻辑上」两条链表接在了一起。

    如果这样进行拼接,就可以让 p1p2 同时进入公共部分,也就是同时到达相交节点 c1

    160. 相交链表 - 力扣(LeetCode)

    1. public class Solution {
    2.    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    3.        ListNode p1 = headA,p2 = headB;
    4.        while(p1 != p2) {
    5.            if(p1 == null) p1 = headB;
    6.            else p1 = p1.next;
    7.            if(p2 == null) p2 = headA;
    8.            else p2 = p2.next;
    9.       }
    10.        return p1;
    11.   }
    12. }

    反转单链表

    递归实现

    递归反转整个链表

    对于递归算法,最重要的就是明确递归函数的定义

    以反转单链表代码为例:

    1. // 定义:输入一个单链表头结点,将该链表反转,返回新的头结点
    2. ListNode reverse(ListNode head) {
    3.    if (head == null || head.next == null) {
    4.        return head;
    5.   }
    6.    ListNode last = reverse(head.next);
    7.    head.next.next = head;
    8.    head.next = null;
    9.    return last;
    10. }
     
    

    具体来说,我们的 reverse 函数定义是这样的:

    输入一个节点 head,将「以 head 为起点」的链表反转,并返回反转之后的头结点。

    所以,递归第一次后,除了第一个位置,其他地方的节点已经被反转,并返回了反转后的头节点。 但这时还没有对整个链表的结构进行处理,也就是说,第二个节点的next = null ,而头节点的next 是第二个节点,那么接下来就是将第二个节点的next指向第一个节点。而第一个节点的next = null。

    递归反转链表前N个节点

    1. ListNode successor = null; // 后驱节点
    2. // 反转以 head 为起点的 n 个节点,返回新的头结点
    3. ListNode reverseN(ListNode head, int n) {
    4.    if (n == 1) {
    5.        // 记录第 n + 1 个节点
    6.        successor = head.next;
    7.        return head;
    8.   }
    9.    // 以 head.next 为起点,需要反转前 n - 1 个节点
    10.    ListNode last = reverseN(head.next, n - 1);
    11.    head.next.next = head;
    12.    // 让反转之后的 head 节点和后面的节点连起来
    13.    head.next = successor;
    14.    return last;
    15. }

    具体的区别:

    1、base case 变为 n == 1,反转一个元素,就是它本身,同时要记录后驱节点

    2、刚才我们直接把 head.next 设置为 null,因为整个链表反转后原来的 head 变成了整个链表的最后一个节点。但现在 head 节点在递归反转之后不一定是最后一个节点了,所以要记录后驱 successor(第 n + 1 个节点),反转之后将 head 连接上。

    反转链表的一部分

    给一个索引区间 [m, n](索引从 1 开始),仅仅反转区间中的链表元素

    首先,如果 m == 1,就相当于反转链表开头的 n 个元素嘛,也就是反转前N个数的功能。

    如果m!=1,把下一个节点视为1的话,就是反转下一个节点后的n个节点,但由于整个链表去掉了1个节点,所以整个链表的总节点数实际上也要比原先的个数少1个。例如:原先如果是从2下标到5下标反转,而总数组有1,6的下标。那么实际上一开始后发现m不满足时,2下标变为1的时候,需要反转的地方就变成1,到4了,也就是都会少一。

    1. ListNode reverseBetween(ListNode head, int m, int n) {
    2.    // base case
    3.    if (m == 1) {
    4.        return reverseN(head, n);
    5.   }
    6.    // 前进到反转的起点触发 base case
    7.    head.next = reverseBetween(head.next, m - 1, n - 1);
    8.    return head;
    9. }

    迭代实现

    25. K 个一组翻转链表 - 力扣(LeetCode)

    1. class Solution {
    2.    
    3.    public ListNode reverseKGroup(ListNode head, int k) {
    4.        if(head == null) return null;
    5.        ListNode start, end;
    6.        start = end = head;
    7.        for(int i = 0 ; i < k ; i++) {
    8.            if(end == null) return head;
    9.            end = end.next;
    10.       }
    11.        ListNode newhead = reverseK(start,end);
    12.        start.next = reverseKGroup(end , k );
    13.        return newhead;
    14.   }
    15.    public ListNode reverseK(ListNode head,ListNode end) {
    16.        ListNode pre = null;
    17.        ListNode now = head;
    18.        ListNode next = head;
    19.        while(now != end) {
    20.            next = now.next;
    21.            now.next = pre;
    22.            pre = now;
    23.            now = next;
    24.       }
    25.        return pre;
    26.   }
    27. }

    实际上也用到了递归的思想,将整个链表看作一个大问题的话,实际上就是每次都要反转前k个节点,直到节点树目不足k个。那么第一次反转k个之后,剩下的就是原链表树目-k个节点的链表,是一个更小的问题,而原先反转完之后,我们希望函数返回的是反转完的头结点,所以,实际中上一次反转的末尾的下一个对应的就是下一次反转函数返回的头结点。

    判断回文链表

    寻找回文串的核心思想是从中心向两端扩展

    1. // 在 s 中寻找以 s[left] 和 s[right] 为中心的最长回文串
    2. String palindrome(String s, int left, int right) {
    3.    // 防止索引越界
    4.    while (left >= 0 && right < s.length()
    5.            && s.charAt(left) == s.charAt(right)) {
    6.        // 双指针,向两边展开
    7.        left--;
    8.        right++;
    9.   }
    10.    // 返回以 s[left] 和 s[right] 为中心的最长回文串
    11.    return s.substring(left + 1, right);
    12. }

    因为回文串长度可能为奇数也可能是偶数,长度为奇数时只存在一个中心点,而长度为偶数时存在两个中心点,所以上面这个函数需要传入 lr

    判断是不是回文串

    1. boolean isPalindrome(String s) {
    2.    // 一左一右两个指针相向而行
    3.    int left = 0, right = s.length() - 1;
    4.    while (left < right) {
    5.        if (s.charAt(left) != s.charAt(right)) {
    6.            return false;
    7.       }
    8.        left++;
    9.        right--;
    10.   }
    11.    return true;
    12. }

    接下来,判断一个单链表是不是回文链表

    这道题的关键在于,单链表无法倒着遍历,无法使用双指针技巧。

    可以思考递归遍历的方法,递归返回时,如果是在返回前,就是顺序遍历,如果是在返回后写就是后序遍历。

    而后序遍历的话,就可以在返回时与前半部分的节点进行比较,就可以知道是不是回文串了。

    234. 回文链表 - 力扣(LeetCode)

    1.    private ListNode left;
    2.    public boolean isPalindrome(ListNode head) {
    3.        left = head;
    4.        return trease(head);
    5.   }
    6.    public boolean trease(ListNode head){
    7.        if(head == null) return true;
    8.        boolean res = trease(head.next);
    9.        
    10.        res = res && (left.val == head.val);
    11.        left = left.next;
    12.        return res;
    13.   }

    这题当然也可以反转链表之后再判断:

    1. class Solution {
    2. public boolean isPalindrome(ListNode head) {
    3. ListNode head2 = new ListNode(head.val);
    4. ListNode p = head.next;
    5. ListNode p2 = head2;
    6. while(p!=null) {
    7. ListNode newNode = new ListNode(p.val);
    8. p2.next = newNode;
    9. p2 = newNode;
    10. p=p.next;
    11. }
    12. head2 = reverse(head2);
    13. while(head2!=null) {
    14. if(head2.val!=head.val) return false;
    15. head = head.next;
    16. head2 = head2.next;
    17. }
    18. return true;
    19. }
    20. public ListNode reverse(ListNode head) {
    21. if(head == null || head.next == null) {
    22. return head;
    23. }
    24. ListNode last = reverse(head.next);
    25. head.next.next = head;
    26. head.next = null;
    27. return last;
    28. }
    29. }

            本文仅作为博主学习过程的记录。建议双指针,虚拟节点的使用以及对于链表递归的写法深入了解。

  • 相关阅读:
    【AOP系列】6.缓存处理
    【每日一题】ABC248C - Dice Sum | 动态规划 |简单
    【JS】浅谈浅拷贝与深拷贝
    Flask 接口
    R语言入门——line和lines的区别
    智能运维应用之道,告别企业数字化转型危机
    医疗领域这个关键技术,你做对了吗?
    3.4 常用操作
    Linux之ssh
    使用百度云服务器申请ssl证书配置报错问题
  • 原文地址:https://blog.csdn.net/C_Ryson/article/details/133654550