fork download
  1. <?php
  2. class ListNode
  3. {
  4. public $val;
  5. public $nxt;
  6. function __construct($val)
  7. {
  8. $this->val = $val;
  9. $this->nxt = NULL;
  10. }
  11.  
  12. function readNode()
  13. {
  14. return $this->val;
  15. }
  16. }
  17.  
  18. class ReverseLinkedList
  19. {
  20. private $first;
  21. private $last;
  22. private $count;
  23.  
  24. function __construct()
  25. {
  26. $this->first = NULL;
  27. $this->last = NULL;
  28. $this->count = 0;
  29. }
  30.  
  31. //insert First Node
  32. public function insertFirst($val)
  33. {
  34. $link = new ListNode($val);
  35. $link->nxt = $this->first;
  36. $this->first = &$link;
  37.  
  38. if($this->last == NULL)
  39. $this->last = &$link;
  40. $this->count++;
  41. }
  42.  
  43. public function show()
  44. {
  45. $listval = array();
  46. $cur = $this->first;
  47. while($cur != NULL)
  48. {
  49. array_push($listval, $cur->readNode());
  50. $cur = $cur->nxt;
  51. }
  52. foreach($listval as $v){
  53. echo $v." ";
  54. }
  55. }
  56.  
  57. public function reverseLinkedList()
  58. {
  59. if($this->first != NULL)
  60. {
  61. if($this->first->nxt != NULL)
  62. {
  63. $cur = $this->first;
  64. $new = NULL;
  65.  
  66. while ($cur != NULL)
  67. {
  68. $temp = $cur->nxt;
  69. $cur->nxt = $new;
  70. $new = $cur;
  71. $cur = $temp;
  72. }
  73. $this->first = $new;
  74. }
  75. }
  76. }
  77.  
  78.  
  79. //insertion at ith key
  80. public function insert($NewItem,$key)
  81. {
  82. if($key == 0){
  83. $this->insertFirst($NewItem);
  84. }
  85. else
  86. {
  87. $link = new ListNode($NewItem);
  88. $cur = $this->first;
  89. $previous = $this->first;
  90.  
  91. for($i=0;$i<$key;$i++)
  92. {
  93. $previous = $cur;
  94. $cur = $cur->nxt;
  95. }
  96.  
  97. $previous->nxt = $link;
  98. $link->nxt = $cur;
  99. $this->count++;
  100. }
  101.  
  102. }
  103. }
  104.  
  105. $o = new ReverseLinkedList();
  106. //$o->insertFirst($value);
  107. //$o->insert($value,$key); // at any index
  108.  
  109. $o->insertFirst(1);
  110. $o->insert(2,1);
  111. $o->insert(3,2);
  112. $o->insert(4,3);
  113. $o->insert(5,4);
  114. $o->reverseLinkedList();
  115. $o->show();
Success #stdin #stdout 0.02s 52472KB
stdin
Standard input is empty
stdout
5 4 3 2 1