0

I am trying to solve a problem to efficiently merge 2 unsorted Linked Lists into one sorted Linked List. I have some ideas.

  1. Simply merge the 2 linked lists and than sort (mergesort or quicksort)
  2. Sort both individually and merge the two follow this concept.

How to merge two sorted arrays into a sorted array?

Those are about all the algorithms I can think of. Does anyone else have any better and more efficient ways to solve this problem?

Community
  • 1
  • 1
Liondancer
  • 15,721
  • 51
  • 149
  • 255

3 Answers3

2

You should just catenate the two lists into a single list and sort that list.

This is more straight forward than sorting them first and is less code and will take the same amount of time as the the second option.

Peter Wooster
  • 6,009
  • 2
  • 27
  • 39
1

First merge both the lists to form a single linked list and then do sort this single list.

Gopi
  • 19,784
  • 4
  • 24
  • 36
1

Another approach will be to use BST. Add list 1 elements into BST, then add list 2 elements in BST. Then use inorder traversal of BST and put elements into the list 3 which will be sorted.

O(nlogn)

zookastos
  • 917
  • 10
  • 37
  • This would give similar performance to doing mergesort on both lists and then merging them, isn't it? – Murphy Oct 18 '16 at 04:34
  • ofcourse. I mentioned that it is O(nlogn). It is efficient space wise. Plus there is no rearranging of elements involved, as there is in mergesort leading to more computation. – zookastos Oct 18 '16 at 15:39