Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- class Node{
- int val;
- Node next;
- Node(int val){
- this.val=val;
- this.next=null;
- }
- }
- public class Main
- {
- public static Node insertAtTail(Node tail,Node newNode){
- tail.next=newNode;
- return newNode;
- }
- public static void print(Node head){
- while(head!=null){
- System.out.print(head.val+" ");
- head=head.next;
- }
- }
- public static Node swap(Node head,int n,int k){
- Node t1=head,t2=head, prev1 = null,prev2 = null;
- for(int i=0;i<k-1;i++){
- prev1 = t1;
- t1=t1.next;
- }
- for(int i=0;i<n-k;i++){
- prev2 = t2;
- t2=t2.next;
- }
- if(t1 == t2) return head;
- int v1 = t1.val;
- int v2 = t2.val;
- t1.val = v2;
- t2.val = v1;
- return head;
- }
- public static void main (String[] args) throws java.lang.Exception
- {
- Scanner sc=new Scanner(System.in);
- int n=sc.nextInt();
- int k=sc.nextInt();
- Node head=null;
- Node tail=head;
- for(int i=0;i<n;i++){
- if(head==null){
- head=new Node(sc.nextInt());
- tail=head;
- }
- else{
- tail=insertAtTail(tail,new Node(sc.nextInt()));
- }
- }
- swap(head,n,k);
- print(head);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement