Given a linked list and an integer n, append the last n elements of the LL to front. Assume given n will be smaller than length of LL.
Input format: Line 1: Linked list elements (separated by space and terminated by -1
Sample Input 1 :
1 2 3 4 5 -1
3
Sample Output 1 :
3 4 5 1 2
Description:
The question asks us to append the last N nodes to front, i.e the new linked list should first start from those N nodes and then traverse the rest of the nodes through the head of the old linked list.
Example:
For Linked List 1->2->3->4->5->6->NULL
To append the last 2 nodes, the new linked list should be:
5->6->1->2->3->4->NULL
To solve this problem, we take two pointers temp and t and point both of them to the head of the linked list. We take another variable i and equate it to – n. This i is used for finding out the head of the new linked list. Then we traverse the loop while temp != NULL. In the loop we check that if(i>=0) i.e temp is now n nodes away from t, t = t-> next. We will update i++ and temp = temp->next on each traversal. At last, we update temp-> next = head, head = t -> next and t-> next = NULL.
Algorithm:
Steps:
At first: 1->2->3->4->5->6->NULL, t->1 and temp->1. After complete traversal: 1->2->3->4->5->6->NULL, t->4 and temp->6. So, temp->next = head and head = t->next i.e 5->6->1->2->3->4 --- (reconnecting to 5) Atlast, t-> next = NULL i.e 5->6->1->2->3->4->NULLFunction:
Node *appendNNodes(Node* head, int n){ // Two pointers, one for traversal and // other for finding the new head of LL Node *temp = head, *t = head; //index maintained for finding new head int i = -n; while(temp->next!=NULL){ //When temp went forward n nodes from t if(i>=0){ t = t->next; } temp = temp ->next; i++; } //Connecting the tail to head temp->next = head; //Assigning the new node head = t->next; //Deleting the previous connection t->next = NULL; return head; }C++ Code:
Output