Skip to content

Instantly share code, notes, and snippets.

@Svastikkka
Created August 23, 2020 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Svastikkka/c28c6ac3b971001f96ef0eed98fadff1 to your computer and use it in GitHub Desktop.
Save Svastikkka/c28c6ac3b971001f96ef0eed98fadff1 to your computer and use it in GitHub Desktop.
## Read input as specified in the question.
## Print output as specified in the question.
class Node:
def __init__(self,data):
self.data=data
self.next=None
def LinkedLists(arr):
head=None
tail=None
for i in arr:
if i==-1:
break
data = Node(i)
if head is None:
head=data
tail=data
else:
tail.next=data
tail=data
return head
def MergeSortedLL(head1,head2):
if head1 == None:
return head2
elif head2 == None:
return head1
mergedHead = None
if head1.data <= head2.data:
mergedHead = head1
head1 = head1.next
else:
mergedHead = head2
head2 = head2.next
mergedTail = mergedHead
while head1 != None and head2 != None:
temp = None
if head1.data <= head2.data:
temp = head1
head1 = head1.next
else:
temp = head2
head2 = head2.next
mergedTail.next = temp
mergedTail = temp
if head1 != None:
mergedTail.next = head1
elif head2 != None:
mergedTail.next = head2
return mergedHead
def printLL(head):
while head is not None:
print(head.data,end=" ")
head=head.next
def printReverse(head) :
prev = None
current = head
while (current is not None):
next = current.next
current.next = prev
prev = current
current = next
head = prev
printLL(head)
arr1 = list(map(int, input().split()))
arr2 = list(map(int, input().split()))
printLL(printReverse(MergeSortedLL(LinkedLists(arr1),LinkedLists(arr2))))
@Svastikkka
Copy link
Author

Merge Two linked lists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment