iT邦幫忙

2023 iThome 鐵人賽

DAY 5
0
自我挑戰組

30天leetcode學習旅程系列 第 5

項次5 - Singly Linked List

  • 分享至 

  • xImage
  •  

Creating a Linked List

public class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

題目:206. Reverse Linked List

連結:https://leetcode.com/problems/reverse-linked-list/description/

  • 等級:Easy

解題思路

  1. 利用temp進行指向方向轉換
class Solution {
    private ListNode rev(ListNode current,ListNode prev)
    {
        if (current == null) return prev;
        ListNode temp = current.next;
        current.next = prev;
        return rev(temp,current);
    }
    public ListNode reverseList(ListNode head) {
            return rev(head,null);
    }
}
  • Time complexity: O(1)
  • Space complexity: O(1)

題目:21. Merge Two Sorted Lists

連結:https://leetcode.com/problems/reverse-linked-list/description/

  • 等級:Easy

解題思路

  1. 利用遞回,並記錄前一個狀態,進行Link merge
class Solution {
    private void mergelist(ListNode curr,ListNode list1,ListNode list2)
    {
        if (list1 == null)
        {
            curr.next = list2;
            return ;
        }
        else if(list2 == null)
        {
            curr.next = list1;
            return;
        }
        else if (list1.val <= list2.val)
        {
            curr.next = list1;
            list1 = list1.next;
        }
        else
        {
            curr.next = list2;
            list2 = list2.next;
        }
        curr = curr.next;
        mergelist(curr,list1,list2);
    }
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode root = new ListNode(0);
        ListNode prev = root;
        mergelist(prev,list1,list2);
        return root.next;
    }
}
  • Time complexity: O(1)
  • Space complexity: O(1)

上一篇
項次4 - Stacks -2
下一篇
項次6-Doubly Linked List
系列文
30天leetcode學習旅程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言