Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- public class Main
- {
- // Node class
- static class Node{
- int data; Node next;
- Node(int val)
- {
- data = val;
- next = null;
- }
- }
- // function to create a LL
- static Node createLL(int len, int[] arr)
- {
- Node head = null, tail = null;
- for(int i = 0; i<len; i++)
- {
- Node newNode = new Node(arr[i]);
- if(head == null)
- {
- head = newNode;
- tail = newNode;
- }
- else
- {
- tail.next = newNode;
- tail = newNode;
- }
- }
- return head;
- }
- // count he number of nodes
- static int countNodes(Node head)
- {
- int cnt = 0;
- while(head != null)
- {
- cnt++;
- head = head.next;
- }
- return cnt;
- }
- // print the LL
- static void printLL(Node head)
- {
- while(head != null)
- {
- System.out.print(head.data+ " ");
- head = head.next;
- }
- }
- // Swap the kth nodes from start and end
- static Node swapKthNode(Node head, int n, int k)
- {
- //base cases
- if(head == null || head.next == null)
- return head;
- // no swapping reqd
- if (k == n-k+1)
- return head;
- else
- {
- Node first = head, second = head;
- Node first_prev = null, second_prev = null;
- for(int i = 1; i<k; i++)
- {
- first_prev = first;
- first = first.next;
- }
- for(int i = 1; i<n-k+1; i++)
- {
- second_prev = second;
- second = second.next;
- }
- if(first_prev != null)
- first_prev.next = second;
- if(second_prev != null)
- second_prev.next = first;
- Node temp = first.next;
- first.next = second.next;
- second.next = temp;
- if(k == 1)
- head = second;
- if(k == n)
- head = first;
- }
- return head;
- }
- public static void main (String[] args) throws java.lang.Exception
- {
- //your code here
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int k = sc.nextInt();
- int arr[];
- arr = new int[n];
- for(int i = 0; i<n; i++)
- arr[i] = sc.nextInt();
- Node head = createLL(n, arr);
- head = swapKthNode(head, n, k);
- printLL(head);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment