## merge two linked sorted list but get unexpected answer

merge two sorted lists - leetcode

merge two sorted lists python

merge two sorted doubly linked lists

merge two sorted linked list without duplicates

merge sort linked list

merge two sorted linked lists python

merge sort linked list leetcode

I wrote such a solution to `merge two sorted list`

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

My solution:

# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution3: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: """ Plan: Compare l1 and l2 and merge the remainders """ head = ListNode(0) #create head to hold l3 = ListNode(0) head.next = l3 while l1 and l2: #assert both exist if l2.val < l1.val: l3 = l2 #build l3's node l2 = l2.next #this is i++ else: l3 = l1 l1 = l1.next l3 = l3.next #find the next to build if l1: l3 = l1 if l2: l3 = l2 return head.next

but get wrong answer

Input

[1,2,4] [1,3,4]

Output

[0]

Expected

[1,1,2,3,4,4]

I checked but cannot find any problems with my logic.

Could you please help me out?

Your `l3`

is supposed to identify the place where a next node shall be appended, hence

l3 = head

You need to append the head of one of lists given (`l1`

or `l2`

) to `l3`

, but you don't.
And after you append the node you need to advance both the head pointer of the source list (`l1`

or `l2`

) and the tail pointer of the destination list (`l3`

):

while l1 and l2: #assert both exist if l2.val < l1.val: l3.next = l2 #append new node to the resulting list l2 = l2.next #and skip it in the source list else: l3.next = l1 l1 = l1.next l3 = l3.next #find the next to build

**Merging two sorted linked lists,** That is, your returned list will never contain more than two nodes, regardless of input It's been a while So far all of the answers have been interesting and well done. It's possible that 2 Down vote. So merging polygen wit AndreyT we get: Problem statement. Given 2 sorted singly linked list. Write a function to merge given two sorted linked lists. List1: 10->15->17->20 List2: 5->9->13->19 Result: 5->9->10->13->15->17->19->20

here is my solution

class ListNode: def __init__(self, x): self.val = x self.next = None def insert(self,el): Node = self while Node: if Node.next==None: Node.next = ListNode(el) break else: Node =Node.next def prin(node): while node: if node.next: print(node.val,end='-> ') else: print(node.val) node = node.next def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: """ Plan: Compare l1 and l2 and merge the remainders """ _node = None if l1.val<l2.val: _node = ListNode(l1.val) l1 =l1.next else: _node = ListNode(l2.val) l2=l2.next l3 = _node while l1 and l2: #assert both exist if l2.val < l1.val: l3.insert(l2.val) l2 = l2.next else: l3.insert(l1.val) l1 = l1.next while l1: l3.insert(l1.val) l1 =l1.next while l2: l3.insert(l2.val) l2 = l2.next return l3 node1= ListNode(1) node1.insert(2) node1.insert(4) node2 = ListNode(1) node2.insert(3) node2.insert(4) solved_list = mergeTwoLists(node1,node2) solved_list.prin()

**Merge two sorted linked lists,** Write a SortedMerge() function that takes two lists, each of which is sorted in For example if the first linked list a is 5->10->15 and the other linked list b is Get hold of all the important DSA concepts with the DSA Self Paced� You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.

Your function returns `head.next`

, which is only modified in the following lines:

l3 = ListNode(0) # this is what's returned head.next = l3 ... # rest of the code changes l3, but never touches head.next return head.next

You seem to assume that, with this setup, any assignments to `l3`

will modify `head.next`

, which is not correct. As it stands, the function will always return the newly created node with content 0.

A more correct approach would be:

# at the beginning l3 = head # l3.next is now actually equivalent to head.next ... # to add a node l3.next = newnode l3 = l3.next # moving the pointer to the newly added tail

**Amazon Coding Interview Question,** Merge Two Sorted Lists is a coding interview question asked by Amazon (and In this video Duration: 14:58
Posted: Feb 15, 2020 I have a function that correctly returns the multiples of 3 and those of 5 in 2 separate linked lists. Now I want to combine those 2 Linked Lists into a single sorted non-repeating Linked List. I tried the following code, but "next" is not a defined element in my case since I'm using the Linked List library.

You're never changing the list structure (there are no assignments to any `next`

s in the loop), you're just moving `l1`

, `l2`

, and `l3`

along the input lists.
Then you return `head.next`

, which is still the node you first assigned to it.

Since your approach with a sentinel node makes the code much simpler than without, I've kept it here:

def merge(l1, l2): first = ListNode(0) # 'here' is where we link in the nodes. here = first while l1 and l2: # Pick the next node from the inputs. # Note that this has the same effect as assigning # to 'first.next' on the first iteration, when 'first' and 'here' # refer to the same object. if l1.val < l2.val: here.next = l1 else: here.next = l2 # Move along to the last node we picked. here = here.next # Grab the rest. if l1: here.next = l1 else: here.next = l2 return first.next

**Using Merge Sort to Sort a Linked List,** Sort the sublists recursively and then merge the sorted lists together to form the answer. STEP 2: Divide the linked list into two equal halves. sort the sublists MergeSort(&b); *headRef = SortedMerge(a, b); // answer = merge the two sorted lists together } SURPRISE ME WITH More Awesome Stuff. Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

Quick solution:

class ListNode: def __init__(self, x): self.val = x self.next = None class Solution3: def merge_two_lists(self, l1: ListNode, l2: ListNode): head = ListNode(None) l3 = ListNode(None) head.next = l3 while l1 and l2: if l2.val < l1.val: l3.next = l2 l2 = l2.next else: l3.next = l1 l1 = l1.next l3 = l3.next if l1: l3.next = l1 if l2: l3.next = l2 head = head.next return head.next head_0, head_0.next, head_0.next.next = ListNode(1), ListNode(2), ListNode(4) head_1, head_1.next, head_1.next.next = ListNode(1), ListNode(3), ListNode(4) no = Solution3().merge_two_lists(head_0, head_1) while no: print("Singly-linked list: {}".format(no.val)) no = no.next

Output:

Singly-linked list: 1 Singly-linked list: 1 Singly-linked list: 2 Singly-linked list: 3 Singly-linked list: 4 Singly-linked list: 4

**What is the shortest function that merges two sorted lists of length 2 ,** Is using insertion sort on a linked list faster than using it on an array? Originally Answered: What is the shortest algorithm to define a function that merges two is even simpler and shorter, but sorted() has already been banned for some� Recursive algorithm for merging two sorted linked lists. def merge_lists(h1, h2): if h1 is None: return h2 if h2 is None: return h1 if (h1.value < h2.value): h1.next = merge_lists(h1.next, h2) return h1 else: h2.next = merge_lists(h2.next, h1) return h2. share.

**sorting - Merge Sort a Linked List - Q&A Vodnicear,** No surprise. The other approaches I tried from this page were two or more times slower. MergeSort naturally fits to linked list and algorithm can be beautiful and These all get merged up into a full sized sorted list. Dave Gamble's non-recursive answer, with a link) but a bit slower than Dave Gamble's recursive code. Merging of two linked lists is the same as the concatenation of two strings. But this time instead of playing with index number we have to play with the address. In this tutorial, we are going to make two linked lists and merging second linked list to first.

**Merge Two Sorted Lists,** Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Remove the common nodes in two Singly Linked Lists; Merge two unsorted linked lists to get a sorted list; Doubly Linked List Tutorial; Sum and Product of all even digit sum Nodes of a Singly Linked List; Sum and Product of nodes with value as even digit sum in Circular Linked List; First Fit algorithm in Memory Management using Linked List

**Linked list,** In computer science, a linked list is a linear collection of data elements whose order is not given A linked list whose nodes contain two fields: an integer value and a link to the next node. Another example is the merging two sorted lists: if their sentinels have data fields set to +∞, the choice of the next output node does � Write a function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order and return it. For example, consider lists {1, 3, 5} and {2, 4, 6, 7}.

##### Comments

- In your loop you never set the
`.next`

so what did you expect to obtain? You simply give different names to different objects without ever doing anything to them. - save the day, could you please transmit the comment to answer.@GiacomoAlzetta
- @Alice I think i have answered your problem
- It may differ but if you still need changes i can comply. I hope you get the code