Advertisement
unknown_0711

Untitled

Jul 6th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. class Node{
  5. int val;
  6. Node next;
  7.  
  8. Node(int val){
  9. this.val=val;
  10. this.next=null;
  11.  
  12. }
  13. }
  14. public class Main
  15. {
  16. public static Node insertAtTail(Node tail,Node newNode){
  17. tail.next=newNode;
  18. return newNode;
  19. }
  20. public static void print(Node head){
  21. while(head!=null){
  22. System.out.print(head.val+" ");
  23. head=head.next;
  24. }
  25. }
  26. public static Node swap(Node head,int n,int k){
  27. Node t1=head,t2=head, prev1 = null,prev2 = null;
  28. for(int i=0;i<k-1;i++){
  29. prev1 = t1;
  30. t1=t1.next;
  31. }
  32. for(int i=0;i<n-k;i++){
  33. prev2 = t2;
  34. t2=t2.next;
  35. }
  36. if(t1 == t2) return head;
  37.  
  38.  
  39. int v1 = t1.val;
  40. int v2 = t2.val;
  41. t1.val = v2;
  42. t2.val = v1;
  43.  
  44.  
  45.  
  46. return head;
  47. }
  48.  
  49. public static void main (String[] args) throws java.lang.Exception
  50. {
  51. Scanner sc=new Scanner(System.in);
  52. int n=sc.nextInt();
  53. int k=sc.nextInt();
  54.  
  55. Node head=null;
  56. Node tail=head;
  57. for(int i=0;i<n;i++){
  58. if(head==null){
  59. head=new Node(sc.nextInt());
  60. tail=head;
  61. }
  62. else{
  63. tail=insertAtTail(tail,new Node(sc.nextInt()));
  64. }
  65. }
  66. swap(head,n,k);
  67. print(head);
  68. }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement