Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static SinglyLinkedList<T> MergeLists<T>(SinglyLinkedList<T> list1, SinglyLinkedList<T> list2) where T : IComparable
- {
- Node<T> head1 = list1.Head;
- Node<T> head2 = list2.Head;
- //SinglyLinkedList<T> mergedList = new SinglyLinkedList<T>();
- // Both lists are empty
- if (head1 == null && head2 == null)
- {
- return null;
- }
- // List 1 is empty
- else if (head1 == null && head2 != null)
- {
- return list2;
- }
- // List 2 is empty
- else if (head2 == null && head1 != null)
- {
- return list1;
- }
- // Both lists are not empty
- else
- {
- Node<T> cursor1 = head1;
- Node<T> cursor2 = head2;
- if (Convert.ToInt32(cursor1.Next.Value) > Convert.ToInt32(cursor2.Value))
- {
- Node<T> temp = cursor1;
- cursor1 = cursor2;
- cursor2 = temp;
- }
- // Add all elements from list 2 to list 1
- while (cursor1.Next != null && cursor2 != null)
- {
- if (Convert.ToInt32(cursor1.Next.Value) < Convert.ToInt32(cursor2.Value))
- {
- cursor1 = cursor1.Next;
- }
- else
- {
- Node<T> temp1 = cursor1.Next;
- Node<T> temp2 = cursor2.Next;
- cursor1.Next = cursor2;
- cursor2.Next = temp1;
- cursor1 = cursor1.Next;
- cursor2 = temp2;
- }
- }
- if (cursor1.Next == null)
- {
- cursor1.Next = cursor2;
- }
- }
- return list2;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement