fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class Node{
  8. private int num;
  9. private Node next;
  10. Node(int num, Node next) {
  11. this.num=num;
  12. this.next=next;
  13. }
  14. public Node getNext(){
  15. return this.next;
  16. }
  17. public void setNext(Node next)
  18. {
  19. this.next=next;
  20. }
  21. public int getNum(){
  22. return this.num;
  23. }
  24.  
  25. public Node reverseSubList(Node head,int p,int q) {
  26. Node node=head;
  27. Node pNodePrev=null,qNodeNext=null;
  28. p--;
  29. q--;
  30. while(node!=null && p>0 ){
  31. pNodePrev=node;
  32. node=node.getNext();
  33. p--;
  34. q--;
  35. }
  36. if(node==null)
  37. return head;
  38.  
  39. Node curr=node,prev=null,next=null;
  40.  
  41. while(curr!=null && q>=0)
  42. {
  43. next=curr.getNext();
  44. curr.setNext(prev);
  45. prev=curr;
  46. curr=next;
  47. q--;
  48. }
  49. if(pNodePrev!=null)
  50. pNodePrev.setNext(prev);
  51. else
  52. head=prev;
  53. prev=null;
  54. while(curr!=null) {
  55. next=curr.getNext();
  56. curr.setNext(prev);
  57. prev=curr;
  58. curr=next;
  59. }
  60. node.setNext(prev);
  61. head=reverseLinkedList(head);
  62. return head;
  63. }
  64. public Node reverseLinkedList(Node head) {
  65.  
  66. Node curr=head,prev=null,next=null;
  67.  
  68. while(curr!=null)
  69. {
  70. next=curr.getNext();
  71. curr.setNext(prev);
  72. prev=curr;
  73. curr=next;
  74. }
  75. return prev;
  76. }
  77. public void printLL(Node node) {
  78. while(node != null){
  79. System.out.print(node.getNum()+" ");
  80. node = node.getNext();
  81. }
  82. System.out.println();
  83. }
  84. }
  85. class Ideone
  86. {
  87. public static void main (String[] args) throws java.lang.Exception
  88. {
  89. Scanner sc = new Scanner(System.in);
  90. int n=sc.nextInt();
  91. int p=sc.nextInt();
  92. int q=sc.nextInt();
  93. Node head = null;
  94. Node node = null;
  95. for(int i=0;i<n;i++)
  96. {
  97. int a=sc.nextInt();
  98. if(head==null){
  99. node = new Node( a,null);
  100. head=node;
  101. }
  102. else{
  103. node.setNext(new Node(a,null));
  104. node = node.getNext();
  105. }
  106.  
  107. }
  108. head=head.reverseSubList(head,p,q);
  109. head.printLL(head);
  110.  
  111. }
  112. }
Success #stdin #stdout 0.12s 35780KB
stdin
7 1 3
1 2 3 4 5 6 7
stdout
4 5 6 7 1 2 3