Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given 2 sorted linked lists, merge them into a new sorted linked list and return head of the merged list. The new list should be made by splicing (adjusting the pointers) together the nodes of the first two lists.
- Input format
- N - An integer denoting the number of nodes in the linked list.
- N integers follow where ith integer denotes the ith node value in the linked list
- M - An integer denoting the number of nodes in the linked list.
- M integers follow where jth integer denotes the jth node value in the linked list
- Output format
- Return the sorted list after splicing the nodes of the first two lists.
- Constraints
- 0 <= N <= 10^5
- -10^9 <= value <= 10^9
- 0 <= M <= 10^5
- -10^9 <= value <= 10^9
- Sample Input 1
- 3
- 1 2 4
- 3
- 1 3 4
- Sample Output 1
- 1 1 2 3 4 4
- Explanation 1
- Merging the input lists and keeping the new list sorted results in this.
- Sample Input 2
- 4
- 1 5 7 6
- 1
- 3
- Sample Output 2
- 1 3 5 7 6
- Explanation 2
- Merging the input lists and keeping the new list sorted results in this.
- */
- /*
- class ListNode{
- constructor(val){
- this.val = val;
- this.next = null;
- }
- */
- /**
- * @param {ListNode} l1
- * @param {ListNode} l2
- * @return {ListNode}
- */
- function mergeTwoLists(l1, l2) {
- let pointer1=l1,pointer2=l2;
- let head=pointer1;
- // pointer1 always poiints to list with smaller value of its first node;
- // now appoerach is i will take pointer1 as parent list and insert other values into this parent list
- if(pointer2==null)
- return pointer1;
- if(pointer1==null)
- return pointer2;
- if(pointer1.val>pointer2.val){
- head=pointer2;
- [pointer1,pointer2]=[pointer2,pointer1];
- }
- // console.log(head)
- while(pointer1.next!=null&&pointer2!=null){
- if(pointer1.next!=null&&pointer1.next.val<pointer2.val){
- pointer1=pointer1.next;
- }
- else{
- let tmp1 = pointer1.next;
- pointer1.next=pointer2;
- let tmp2 = pointer2.next;
- pointer2.next = tmp1;
- // move one step forward
- pointer1 = pointer1.next;
- pointer2 = tmp2;
- }
- }
- if(pointer2==null){
- return head;
- }
- else{
- // pointer1.next===null
- pointer1.next=pointer2;
- }
- return head;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement