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 :
Output format :
Constraints :
1 <= n <= 10^4
Sample Input :
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
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
## 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
Post a Comment
Please give us your valuable feedback