Advertisement
unknown_0711

Untitled

Feb 22nd, 2023
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3. class Node
  4. {
  5. int data;
  6. Node next;
  7. Node(int d) {data = d; next = null; }
  8. }
  9. class insertion
  10. {
  11. Node head;
  12. Node tail;
  13. public void addToTheLast(Node node)
  14. {
  15. if (head == null)
  16. {
  17. head = node;
  18. tail = node;
  19. }
  20. else
  21. {
  22. tail.next = node;
  23. tail = node;
  24. }
  25. }
  26. void printList(Node head)
  27. {
  28. Node temp = head;
  29. while (temp != null)
  30. {
  31. System.out.print(temp.data + " ");
  32. temp = temp.next;
  33. }
  34. System.out.println();
  35. }
  36. /* Drier program to test above functions */
  37.  
  38. }
  39. class Main
  40. {
  41. public static void main(String args[])throws IOException
  42. {
  43. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  44.  
  45. String S[] = br.readLine().split(" ");
  46. int N = Integer.parseInt(S[0]);
  47. int m = Integer.parseInt(S[1]);
  48. int n = Integer.parseInt(S[2]);
  49.  
  50. String S1[] = br.readLine().split(" ");
  51. insertion llist = new insertion();
  52. int a1 = Integer.parseInt(S1[0]);
  53. Node head = new Node(a1);
  54. llist.addToTheLast(head);
  55. for (int i = 1; i < N; i++)
  56. {
  57. int a = Integer.parseInt(S1[i]);
  58. llist.addToTheLast(new Node(a));
  59. }
  60.  
  61. Solution ob = new Solution();
  62. Node newhead = ob.reverseBetween(llist.head, m, n);
  63. llist.printList(newhead);
  64. }
  65. }
  66.  
  67. class Solution
  68. {
  69.  
  70. public static Node reverse(Node head) {
  71. Node prev = null;
  72. Node curr = head;
  73. Node next = head.next;
  74. while (curr != null) {
  75. next = curr.next;
  76. curr.next = prev;
  77. prev = curr;
  78. curr = next;
  79. }
  80. return prev;
  81. }
  82. public static Node reverseBetween(Node head, int m, int n)
  83. {
  84. if (m == n)
  85. return head;
  86. Node ret = new Node(0);
  87. ret.next = head;
  88. Node l = ret;
  89. for (int i = 0; i < n; i++) {
  90. if (i+1 == m) {
  91. // a= 2
  92. Node a=head;
  93. Node prev=null;
  94. Node curr = head;
  95. Node next = head.next;
  96. while (i!=n) {
  97. i++;
  98. next = curr.next;
  99. curr.next = prev;
  100. prev = curr;
  101. curr = next;
  102. }
  103. l.next=prev;
  104. a.next=next;
  105. return ret.next;
  106. }
  107.  
  108. l = head;
  109. head = head.next;
  110. }
  111. return ret.next;
  112. }
  113. }
  114.  
  115.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement