In: Computer Science
In python I have a linked list. I want to create one function that takes in one parameter, head. In the function, cur = head and next_cur = head.next. I want to return head and next_cur, except at the end of the function they will return alternating values from head.
For example, if the these are the values in the linked list:
2, 3, 5, 7, 11
after the function head should return:
2, 5, 11
and next_cur should return:
3, 7
Python3 code:
class Node:
def __init__(self, val=None):
self.val = val
self.nextVal = None
class LinkedList:
def __init__(self):
self.head = None
def getCurr_NextCurr(head):
if(head==None):
return None,None
#initializing with dummy node
curr_list = Node(0)
#initializing with dummy node
next_curr_list = Node(0)
curr = head
#flag to indicate which list to add to
flag = True
pointer1 = curr_list
pointer2 = next_curr_list
while(curr!=None):
if(flag):
#add to curr_list
pointer1.nextVal = Node(curr.val)
pointer1 = pointer1.nextVal
else:
#add to next_curr_list
pointer2.nextVal = Node(curr.val)
pointer2 = pointer2.nextVal
flag = not flag
curr = curr.nextVal
#returning next value since there is a dummy node
return curr_list.nextVal, next_curr_list.nextVal
def display(head):
while(head!=None):
print(head.val,end=" ")
head = head.nextVal
print()
l = LinkedList()
l.head = Node(2)
l.head.nextVal = Node(3)
l.head.nextVal.nextVal = Node(5)
l.head.nextVal.nextVal.nextVal = Node(7)
l.head.nextVal.nextVal.nextVal.nextVal = Node(11)
l1,l2 = getCurr_NextCurr(l.head)
display(l1)
display(l2)
Output:
2 5 11
3 7
Note:
I have also written a display() to check the result for different inputs