Swap Kth nodes from ends | Practice | GeeksforGeeks

Given a singly linked list of size N, and an integer K. You need to swap the Kth node from the beginning and Kth node from the end of the linked list. Swap the nodes through the links. Do not change the content of the nodes.
 
Example 1:
Input:
N = 4,  K = 1
value[] = {1,2,3,4}
Output: 1
Explanation: Here K = 1, hence after
swapping the 1st node from the beginning
and end thenew list will be 4 2 3 1.

 
Example 2:
Input:
N = 5,  K = 7
value[] = {1,2,3,4,5}
Output: 1
Explanation: K > N. Swapping is invalid. 
Return the head node as it is.

 
Your Task: 
You do not need to read input or print anything. The task is to complete the function swapkthnode(), which has takes head of link list, N and K as input parameters and returns the new head.
The generated output will be 1 if you are able to complete your task. 
 
Expected Time Complexity: O(n)
Expected Auxillary space Complexity: O(1)
 
Constraints:
1 <= N <= 103
1 <= K <= 103
 
0
nareshshiva9317
This comment was deleted.
0
shakshamkaushik11 week ago
Time  --0.63    Node swapkthnode(Node head, int num, int K)   {       if(K > num){           return head;       }       Node first = head;       Node second = head;       Node prev1 = null;       Node prev2 = null;       for(int i = 1; i<K ;i++){           prev1 = first;           first = first.next;       }       for(int i = 1; i<num - K+1 ;i++){           prev2 = second;           second = second.next;       }       if(prev1!=null){           prev1.next = second;       }       if(prev2!=null){           prev2.next = first;       }       Node temp = first.next;       first.next = second.next;       second.next = temp;              if(K == 1){           head = second;       }       if(K == num){           head = first;       }       return head;              }} 
0
jagannath23sahoo2 weeks ago
C++ Solution
TC: O(1)
Aux SC: O(1)
Node *swapkthnode(Node* head, int n, int k)
{
    Node* start = head;
    Node* end = head;
    Node* prev_start = NULL;
    Node* prev_end = NULL;
    
    if(k>n )
        return head;
    //Moving start ptr
    for(int i = 1; i<k; i++)
    {
        prev_start = start;
        start = start->next;
    }
    
    //Moving end ptr
    for(int i = 1; i<n-k+1; i++)
    {
        prev_end = end;
        end = end->next;
    }
    
    if(prev_start != NULL)
        prev_start->next = end;
    if(prev_end != NULL)
        prev_end->next = start;
    
    Node *temp = end->next;
    end->next = start->next;
    start->next = temp;
    
    if(k == 1)
        head = end;
    if(k == n)
        head = start;
    return head;
}
-1
shalini21sirothiya1 month ago
//c++
Node *swapkthnode(Node* head, int n, int k){   // Your Code here  if(k>n ||k==(n-k+1))  return head;  Node*start=head,*start_prev=NULL;  for(int i=1;i<k;i++){      start_prev=start;      start=start->next;  }  Node*end=head,*end_prev=NULL;  for(int i=1;i<n-k+1;i++){      end_prev=end;      end=end->next;  }  if(start_prev!=NULL)  start_prev->next=end;  if(end_prev!=NULL)  end_prev->next=start;  Node*temp=start->next;  start->next=end->next;  end->next=temp;  if(k==1)  head=end;  if(k==n)  head=start;  return head;}
0
wjyjobs1 month ago
def printn(n):
    while n:
        print(n.data)
        n = n.next
        
def swapkthnode(head,num,k):
    if k > num:
        return head
    dummy = Node(-1)
    dummy.next = head
    
    f = dummy
    for i in range(k-1):
        f = f.next
        
    s = dummy
    for i in range(num-k):
        s = s.next

    # f fn fnn s sn snn 
    fn = f.next
    sn = s.next
    f.next = sn
    s.next = fn
    fn.next, sn.next = sn.next, fn.next

    #printn(dummy.next)
    return dummy.next
0
singhkunal01Premium1 month ago
[C++] Solution using Simple 1 Iteration and finding the Right Nodes To be Swapped using MATHs.
 
Node *swapkthnode(Node* head, int n, int k)
{
  Node *prev1, *node1, *node2, *copy = new Node(-1);
  prev1 = node1 = node2  = copy;
  copy->next = head;
  if (k > n) {return copy->next;}
  int ct = 1, fromLast = n - k + 1;//take some test cases then you can observe that kth node from last is this
  
  while (head) {
    prev1 = head;
    head = head->next;
    ct++;
    if (ct == k) {
      node1 = prev1;
    }
    else if (ct == fromLast) {
      node2 = prev1;
    }
  }
  swap(node1->next, node2->next);
  swap(node1->next->next, node2->next->next);
  return copy->next;
}

-1
abhishekkumar471681 month ago
C++ Solution Straight forward
 
 
Node *swapkthnode(Node* head, int num, int k)
{
   Node*temp1 = head, *temp2 = head, *temp3 = head, *temp4 = NULL, *temp5 = NULL, *temp6 = NULL;
    if (k > num)
        return head;

    if (k == 1 || k == num)
    {
        while (temp3->next != NULL)
        {
            temp4 = temp3; 
            temp3 = temp3->next; 
        }
        temp3->next = head->next;
        temp4->next=head;
        head->next = NULL;
        return temp3;
    }
    int j = 1;
    while (j != k)
    {
        temp4 = temp3;
        temp3 = temp3->next;
        j++;
    }
    j = 1;
    while (j != num - k + 1)
    {
        temp6 = temp2;  
        temp2 = temp2->next; 
        j++;
    }
    if (temp3 == temp2)
        return head;
    if (temp3->next == temp2)
    {
        temp3->next = temp2->next;
        temp2->next = temp3;
        temp4->next = temp2;
        return head;
    }

    if (temp2->next == temp3)
    {
        temp2->next = temp3->next;
        temp3->next = temp2;
        temp6->next = temp3;
        return head;
    }

    temp5 = temp2->next;
    temp2->next = temp3->next;
    temp6->next = temp3;
    temp4->next = temp2;
    temp3->next = temp5;
    return head;
}
+1
rohit_iiitl1 month ago
Node *swapkthnode(Node* head, int num, int K) {
    Node *dummy = new Node(-1), *p1 = dummy, *p2 = dummy;
    dummy -> next = head;
    while(--K) {
        p1 = p1->next;
        if(p1->next == NULL)
            return head;
    }
    Node* temp = p1 -> next;
    p2 = dummy;
    while(temp->next != NULL) {
        p2 = p2 -> next;
        temp = temp -> next;
    }
    swap(p1->next, p2->next);
    swap(p1->next->next, p2->next->next);
    return dummy->next;
}
+1
gargishant1 month ago
Please go through it for easy explanation and efficient approach discussion
https://youtu.be/8968djfWLME
0
6288261 month ago
Straightforward, without tricks.
 
if (K > num)
	return head;
	
Node *pre_kth_from_head = NULL;
Node *kth_from_head = head;

for (int i = 1; i < K; ++i)
{
	pre_kth_from_head = kth_from_head;
	kth_from_head = kth_from_head->next;
}
	
//cout << (pre_kth_from_head ? pre_kth_from_head->data : -1) << " ";
//cout << (kth_from_head ? kth_from_head->data : -1) << " ";

Node *pre_kth_from_tail = NULL;
Node *kth_from_tail = head;
Node *tail = kth_from_head->next;

while (tail)
{
	pre_kth_from_tail = kth_from_tail;
	kth_from_tail = kth_from_tail->next;
	tail = tail->next;
}

//cout << (pre_kth_from_tail ? pre_kth_from_tail->data : -1) << " ";
//cout << (kth_from_tail ? kth_from_tail->data : -1) << endl;

if (pre_kth_from_tail == NULL)
{
	swap(pre_kth_from_tail, pre_kth_from_head);
	swap(kth_from_tail, kth_from_head);
}

if (pre_kth_from_head == NULL)
{
	kth_from_tail->next = kth_from_head->next;
	pre_kth_from_tail->next = kth_from_head;
	kth_from_head->next = NULL;
	head = kth_from_tail;
}
else
{
	pre_kth_from_head->next = pre_kth_from_tail->next;
	pre_kth_from_tail->next = kth_from_head;
	
	Node *tmp = kth_from_tail->next;
	kth_from_tail->next = kth_from_head->next;
	kth_from_head->next = tmp;
}

return head;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.