Let last be the first

Write a function that moves the last element to the front in a given singly Linked List.

For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4.

You just need to return the head of the new linked list, don't print the elements.

Input format :
Line 1 : Linked list elements of length n (separated by space and terminated by -1)
Output format :
Updated list elements (separated by space)
Constraints :

1 <= n <= 10^4

Sample Input :
 1 2 3 4 5 6 -1

Note: -1 at the end of input is just a terminator representing the end of linked list. This -1 is not part of the linked list. Size of given linked list is 6.

Sample Output :
 6 1 2 3 4 5
## 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
if len(arr)<1:
return -1
else:
for i in arr:
if i == -1:
break
NewNode = Node(i)
if head==None:
head=NewNode
tail=NewNode
else:
tail.next=NewNode
tail=NewNode
return head
def appendLastNToFirst(head,k):
h0=head
total = 1
while ( h0 is not None):
h0 = h0.next
total += 1
current = head
count = 1
while (count < total-k-1 and current is not None):
current = current.next
count += 1
NewNode=current
while (current.next is not None):
current = current.next
current.next = head
head = NewNode.next
NewNode.next = None
printLL(head)
def printLL(head):
while head is not None:
print(head.data,end=" ")
head=head.next
arr=list(map(int,input().split()))
appendLastNToFirst(LinkedLists(arr),1)

Comments

Popular posts from this blog

MySQL Multi Source Master Slave Replication using GTID

Access and modify all the resources of our Wiki.js using WikiJS API

How to setup an Nginx reverse proxy with a SSL certificate in XWIKI