Last active
December 3, 2020 07:45
-
-
Save ishank-dev/5995f499c82c959075e4802a047dd812 to your computer and use it in GitHub Desktop.
Coding Question asked in coding interview paytm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
# Constructor to initialize the node object | |
def __init__(self, data): | |
self.data = data | |
self.next = None | |
class LinkedList: | |
# Function to initialize head | |
def __init__(self): | |
self.head = None | |
def size(self): | |
temp = self.head | |
count = 0 | |
while(temp): | |
count += 1 | |
temp = temp.next | |
return count | |
def reverseEvenCase(self): | |
first_half = [] | |
second_half = [] | |
n = self.size() | |
count = 0 | |
temp = self.head | |
while(count != n): | |
if count < n//2: | |
first_half.append(temp.data) | |
else: | |
second_half.append(temp.data) | |
temp = temp.next | |
count += 1 | |
# Reversing the two lists | |
temp = self.head | |
while(temp!=None): | |
if first_half: | |
temp.data = first_half.pop() | |
elif second_half: | |
temp.data = second_half.pop() | |
temp = temp.next | |
def reverseOddCase(self): | |
first_half = [] | |
second_half = [] | |
n = self.size() | |
count = 0 | |
temp = self.head | |
while(temp!=None): | |
if count < n//2: | |
first_half.append(temp.data) | |
elif count == n//2: | |
temp = temp.next | |
count+=1 | |
if count > n//2: | |
second_half.append(temp.data) | |
temp = temp.next | |
count += 1 | |
print(first_half,second_half) | |
# Reversing the two lists ensuring middle node is in its place | |
temp = self.head | |
count = 0 | |
while(temp!=None): | |
count+=1 | |
if first_half: | |
temp.data = first_half.pop() | |
elif second_half: | |
# print(temp.data) | |
temp.data = second_half.pop() | |
if count == n//2: | |
temp = temp.next | |
temp = temp.next | |
# Function to insert a new node at the beginning | |
def push(self, new_data): | |
new_node = Node(new_data) | |
new_node.next = self.head | |
self.head = new_node | |
# Utility function to print the linked LinkedList | |
def printList(self): | |
temp = self.head | |
while(temp): | |
print (temp.data,end = ' ') | |
temp = temp.next | |
print() | |
# Driver code | |
llist = LinkedList() | |
# Uncomment the below line to see the odd case | |
# llist.push(7) | |
llist.push(6) | |
llist.push(5) | |
llist.push(4) | |
llist.push(3) | |
llist.push(2) | |
llist.push(1) | |
print ("Given Linked List") | |
llist.printList() | |
n = llist.size() | |
if n%2 == 0: | |
llist.reverseEvenCase() | |
else: | |
llist.reverseOddCase() | |
llist.printList() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment