Advertisement
unknown_0711

Untitled

Oct 15th, 2022
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1.  
  2. import java.util.*;
  3. import java.lang.*;
  4. import java.io.*;
  5.  
  6. class Node {
  7. int data;
  8. Node next;
  9.  
  10. Node(int data) {
  11. this.data = data;
  12. this.next = null;
  13. }
  14. }
  15.  
  16. public class Main {
  17. public static Node insertAtEnd(int data, Node head) {
  18. Node curr = head;
  19. Node newnode = new Node(data);
  20. if (head == null) {
  21. return newnode;
  22. }
  23.  
  24. while (curr.next != null) {
  25. curr = curr.next;
  26. }
  27. curr.next = newnode;
  28. return head;
  29. }
  30.  
  31. public static void swapNode(Node head, int k, int n) {
  32.  
  33. Node curr1 = head;
  34. Node curr2 = head;
  35. if (head == null || head.next == null) {
  36. return;
  37. }
  38. for (int i = 0; i < k-1; i++) {
  39. curr1 = curr1.next;
  40. }
  41.  
  42. for (int i = 0; i < n-k; i++) {
  43. curr2 = curr2.next;
  44. }
  45. // System.out.println(curr1.data +" "+ curr2.data);
  46. // int tmp = curr1.data;
  47. // curr1.data = curr2.data;
  48. // curr2.data = tmp;
  49. Node cn=curr1.next.next;
  50. Node sn= curr2.next.next;
  51. Node cc= curr1.next;
  52. Node sc= curr2.next;
  53.  
  54. curr1.next=sc;
  55. sc.next=cn;
  56.  
  57. curr2.next=cc;
  58. cc.next=sn;
  59.  
  60.  
  61. }
  62.  
  63. public static void printList(Node head) {
  64. Node curr = head;
  65. while (curr != null) {
  66. System.out.print(curr.data + " ");
  67. curr = curr.next;
  68. }
  69. System.out.println();
  70. }
  71.  
  72. public static void main(String[] args) throws java.lang.Exception {
  73. Scanner sc = new Scanner(System.in);
  74. Node head = null;
  75. int n = sc.nextInt();
  76. int k = sc.nextInt();
  77. head = insertAtEnd(-1, head);
  78. for (int i = 0; i < n; i++) {
  79. int data = sc.nextInt();
  80. head = insertAtEnd(data, head);
  81. }
  82. k=Math.min(k, n-k+1);
  83. // printList(head);
  84. swapNode(head, k, n);
  85. printList(head.next);
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement