1669 Merge in Between Linked Lists – Leetcode

Approach

Find the node at index a – 1 and b
Set the next of the node at index
Find the last node of list2
Set the next of the last node of list2 to the next of the node at index b
Return the head of the list

Complexity


This content originally appeared on DEV Community and was authored by Leetcode

Approach

  • Find the node at index a - 1 and b
  • Set the next of the node at index
  • Find the last node of list2
  • Set the next of the last node of list2 to the next of the node at index b
  • Return the head of the list

Complexity

Time complexity: O(n)

Space complexity: O(1)

Java Code

class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode start = list1;
        ListNode end = list1;
        for (int i = 0; i < a - 1; i++) {
            start = start.next;
        }
        for (int i = 0; i < b; i++) {
            end = end.next;
        }
        start.next = list2;
        while (list2.next != null) {
            list2 = list2.next;
        }
        list2.next = end.next;
        return list1; 
    }
}


This content originally appeared on DEV Community and was authored by Leetcode


Print Share Comment Cite Upload Translate Updates
APA

Leetcode | Sciencx (2024-07-20T04:22:23+00:00) 1669 Merge in Between Linked Lists – Leetcode. Retrieved from https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/

MLA
" » 1669 Merge in Between Linked Lists – Leetcode." Leetcode | Sciencx - Saturday July 20, 2024, https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/
HARVARD
Leetcode | Sciencx Saturday July 20, 2024 » 1669 Merge in Between Linked Lists – Leetcode., viewed ,<https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/>
VANCOUVER
Leetcode | Sciencx - » 1669 Merge in Between Linked Lists – Leetcode. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/
CHICAGO
" » 1669 Merge in Between Linked Lists – Leetcode." Leetcode | Sciencx - Accessed . https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/
IEEE
" » 1669 Merge in Between Linked Lists – Leetcode." Leetcode | Sciencx [Online]. Available: https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/. [Accessed: ]
rf:citation
» 1669 Merge in Between Linked Lists – Leetcode | Leetcode | Sciencx | https://www.scien.cx/2024/07/20/1669-merge-in-between-linked-lists-leetcode/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.