1 <?php
 2     #逆转单链表
 3     class Node {
 4         public $data = null;
 5         public $next = null;
 6     }
 7 
 8     #递归版本
 9     #思想是一直递归到倒数第二个非空节点,并将其next->next指向自己,将自己的next指向null
10     #为了获得逆转后的头结点,在最后一个非空节点,即cnode->next == null时,将节点返回
11     function reverse_list_r($node) {
12         if ($node->next == null) {
13             return $node;
14         } else {
15             $head = reverse_list_r($node->next);
16             $node->next->next = $node;
17             $node->next = null;
18             return $head;
19         }
20     }
21 
22     #非递归版本
23     #思想是需要保存下三个节点,分别是cnode,next(cnode->next),next2(cnode->next->next)
24     #每次要执行的操作只有将next->next指向cnode,然后依次将这三个节点后移,直到next == null
25     function reverse_list($head) {
26         $cnode = $head;
27         $next = $head->next;
28         $head->next = null;
29         while ($next != null) {
30             $next2 = $next->next;
31             $next->next = $cnode; 
32             $cnode = $next;
33             $next = $next2;
34         }
35 
36         return $cnode;
37     }
38 
39     #遍历单链表
40     function traverse($head) {
41         $cnode = $head;
42         while ($cnode != null) {
43             echo $cnode->data . " ";
44             $cnode = $cnode->next;
45         }
46         echo "<br>";
47     }
48 
49     $head = new Node();
50     $n1 = new Node();
51     $n2 = new Node();
52     $n3 = new Node();
53     $head->data = 0;
54     $n1->data = 1;
55     $n2->data = 2;
56     $n3->data = 3;
57     $head->next = $n1;
58     $n1->next = $n2;
59     $n2->next = $n3;
60     $n3->next = null;
61     traverse($head);
62 
63     $rhead = reverse_list_r($head);
64     traverse($rhead);
65 
66     $rrhead = reverse_list($rhead);
67     traverse($rrhead);
68 ?>

0 1 2 3 
3 2 1 0 
0 1 2 3

posted on 2012-09-28 23:32  ZimZz  阅读(382)  评论(0编辑  收藏  举报