Advertisement
BSO90

Untitled

Aug 18th, 2021
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. public static SinglyLinkedList<T> MergeLists<T>(SinglyLinkedList<T> list1, SinglyLinkedList<T> list2) where T : IComparable
  2.         {
  3.             Node<T> head1 = list1.Head;
  4.             Node<T> head2 = list2.Head;
  5.            
  6.             //SinglyLinkedList<T> mergedList = new SinglyLinkedList<T>();
  7.             // Both lists are empty
  8.             if (head1 == null && head2 == null)
  9.             {
  10.                 return null;
  11.             }
  12.             // List 1 is empty
  13.             else if (head1 == null && head2 != null)
  14.             {
  15.                 return list2;
  16.             }
  17.             // List 2 is empty
  18.             else if (head2 == null && head1 != null)
  19.             {
  20.                 return list1;
  21.             }
  22.             // Both lists are not empty
  23.             else
  24.             {
  25.                 Node<T> cursor1 = head1;
  26.                 Node<T> cursor2 = head2;
  27.  
  28.                 if (Convert.ToInt32(cursor1.Next.Value) > Convert.ToInt32(cursor2.Value))
  29.                 {
  30.                     Node<T> temp = cursor1;
  31.                     cursor1 = cursor2;
  32.                     cursor2 = temp;
  33.                 }
  34.  
  35.                 // Add all elements from list 2 to list 1
  36.                 while (cursor1.Next != null && cursor2 != null)
  37.                 {
  38.                     if (Convert.ToInt32(cursor1.Next.Value) < Convert.ToInt32(cursor2.Value))
  39.                     {
  40.                         cursor1 = cursor1.Next;
  41.                     }
  42.                     else
  43.                     {
  44.                         Node<T> temp1 = cursor1.Next;
  45.                         Node<T> temp2 = cursor2.Next;
  46.                         cursor1.Next = cursor2;
  47.                         cursor2.Next = temp1;
  48.  
  49.                         cursor1 = cursor1.Next;
  50.                         cursor2 = temp2;
  51.                     }
  52.                 }
  53.  
  54.                 if (cursor1.Next == null)
  55.                 {
  56.                     cursor1.Next = cursor2;
  57.                 }
  58.             }
  59.          
  60.             return list2;
  61.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement