leetcode高频题笔记之链表

环形链表

在这里插入图片描述
解法一:记录查找法

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<ListNode>();
        ListNode node = head;
        while (node != null) {

            if (set.contains(node)) {
                return true;
            }

            set.add(node);
            node = node.next;
        }

        return false;
    }
}

解法二:快慢指针法(背下来就好了,真的想不到)

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public boolean hasCycle(ListNode head) {

        if (head == null || head.next == null) {
            return false;
        }

        ListNode fast = head.next;
        ListNode slow = head;

        while (fast != slow) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

合并两个有序链表

在这里插入图片描述
要点:保留一个pre标记,让一个新的指针去遍历

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        //如果l1空了,就把l2接上去
        if (l1 == null) {
            cur.next = l2;
        } else {
            cur.next = l1;
        }
        return pre.next;
    }
}

反转链表

在这里插入图片描述

迭代法:原地反转

在这里插入图片描述

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null){
            ListNode tmp = cur.next;
            cur.next  = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

递归:
在这里插入图片描述

public class Solution {
    public ListNode reverseList(ListNode head) {
        //递归终止条件
        if (head == null || head.next == null) {
            return head;
        }
        //下探
        ListNode cur = reverseList(head.next);
        
        head.next.next = head;
        head.next = null;
        //每一次都返回最后一个节点
        return cur;
    }
}

图片引自leetcode题解

发布了40 篇原创文章 · 获赞 85 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41170102/article/details/104909246
今日推荐