算法刷题笔记二

123 阅读1分钟

今日AC了关于链表类的相关题目,在此记录。

leetcode24:两两交换链表中的节点
原文链接:leetcode-cn.com/problems/sw…
思路:假如一个链表1-2-3-4,给它加一个头节点0-1-2-3-4。理清两两交换时链表指向的顺序,我要交换1,2节点。先1的前面一个节点0->2,在1->3,在2->1即可完成。

public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        //建立头节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy; 
        while(pre.next != null && pre.next.next !=null){
            ListNode start = pre.next;
            ListNode end = pre.next.next;
            pre.next = start.next;
            start.next = end.next;
            end.next = start;
            pre = start;
        }
        return dummy.next;
    }

leetcode83:删除链表中的重复元素
原文链接:leetcode-cn.com/problems/re…
思路:遇到重复的元素跳过即可

   public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy.next;
        while(pre != null && pre.next != null){
            if(pre.val == pre.next.val)
                pre.next = pre.next.next;
            else
                pre = pre.next;
        }
        return dummy.next;
    }

leetcode141:判断链表是否有环
原文链接:leetcode-cn.com/problems/li…
思路:
(1):用hash表,出现了相同的元素即为true。时间复杂度O(n),空间复杂度O(n)
(2):快慢指针法,假想为一个操场,跑的快的势必会追上跑得慢的。实际复杂度O(n),空间复杂第O(1)

 public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null)
            return false;
        ListNode fast = head;
        ListNode slow = fast;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast)
                return true;
        }
        return false;
    }

leetcode142:寻找环形链表的入环节点
原文链接:leetcode-cn.com/problems/li…
思路:(1)先判断是否有环。(2)根据数学规律寻找入环节点。
视频讲解教程:www.bilibili.com/video/av528…

    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null)
            return null;
        boolean isCycle = false;
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
                isCycle = true;
                break;
            }
        }
        ListNode p = head;
        if (isCycle) {
            while (p != slow) {
                p = p.next;
                slow = slow.next;
            }
            return slow;
        }
        return null;
    }