fork download
  1. // Swap Nodes in pairs
  2. class Node
  3. {
  4. int v;
  5. Node next;
  6. public Node(int x)
  7. {
  8. v=x;
  9. next=null;
  10. }
  11. }
  12. {
  13. private static Node head=null;
  14. private static int len=0;
  15. private Node swapNodeUtil(Node node)
  16. {
  17. if(node==null || node.next==null)return node;
  18. Node next=swapNodeUtil(node.next.next);
  19. Node temp=node.next;
  20. node.next=next;
  21. temp.next=node;
  22. return temp;
  23. }
  24. public void swapNode()
  25. {
  26. head=this.swapNodeUtil(head);
  27. }
  28. public void add(int x)
  29. {
  30. len++;
  31. Node n=new Node(x);
  32. if(head==null)
  33. head=n;
  34. else
  35. {
  36. Node i=head;
  37. for(;i.next!=null;i=i.next);
  38. i.next=n;
  39. }
  40. }
  41. public int get(int x)
  42. {
  43. int i=0;
  44. Node j=head;
  45. while(i!=x){
  46. j=j.next;
  47. i++;
  48. }
  49. return j.v;
  50. }
  51. public int length()
  52. {
  53. return len;
  54. }
  55. }
  56. public class Main
  57. {
  58. public static void main(String[] args) {
  59. for(int i=0;i<7;i++)l.add(i+1);
  60. l.swapNode();
  61. for(int i=0;i<7;i++)System.out.println(l.get(i));
  62. }
  63. }
  64.  
Success #stdin #stdout 0.11s 320576KB
stdin
Standard input is empty
stdout
2
1
4
3
6
5
7