AppendLastNToFirst
You have been given a singly linked list of integers along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list.
Input format :
Remember/Consider :
Output format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
Explanation to Sample Input 2 :
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: | |
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 = 0 | |
while (h0 is not None): | |
h0 = h0.next | |
total += 1 | |
if total<k: | |
return None | |
current = head | |
count = 1 | |
while (count < total - k 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 --> None | |
head = NewNode.next #head --- NewNode | |
NewNode.next = None | |
printLL(head) | |
def printLL(head): | |
while head is not None: | |
print(head.data, end=" ") | |
head = head.next | |
print() | |
t = int(input()) | |
for i in range(t): | |
arr = list(map(int, input().split())) | |
n = int(input()) | |
appendLastNToFirst(LinkedLists(arr), n) |
Comments
Post a Comment
Please give us your valuable feedback