本篇文章给大家带来的内容是关于php如何实现反转链表(代码实例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1.常见方法分为迭代和递归,迭代是从头到尾,递归是从尾到头
2.设置两个指针,old和new,每一项添加在new的后面,新链表头指针指向新的链表头
3.old->next不能直接指向new,而是应该设置一个临时指针tmp,指向old->next指向的地址空间,保存原链表数据,然后old->next指向new,new往前移动到old处new=old,最后old=tmp取回数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php class Node{ public $data ; public $next ; } //头插法创建一个链表 $linkList = new Node(); $linkList ->next=null; //头结点 for ( $i =1; $i <=10; $i ++){ $node = new Node(); $node ->data= "aaa{$i}" ; //创建新结点$node $node ->next= $linkList ->next; //$node->next指向头结点->next $linkList ->next= $node ; //头结点->next指向$node } var_dump( $linkList ); function ReverseList( $pHead ){ $old = $pHead ->next; //跳过头结点 $new =null; $tmp =null; //反转过程 while ( $old !=null){ $tmp = $old ->next; $old ->next= $new ; $new = $old ; $old = $tmp ; } //给新链表加个头结点 $newHead = new Node(); $newHead ->next= $new ; var_dump( $newHead ); } ReverseList( $linkList ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | object(Node)#1 (2) { [ "data" ]=> NULL [ "next" ]=> object(Node)#11 (2) { [ "data" ]=> string(5) "aaa10" [ "next" ]=> object(Node)#10 (2) { [ "data" ]=> string(4) "aaa9" [ "next" ]=> object(Node)#9 (2) { [ "data" ]=> string(4) "aaa8" [ "next" ]=> object(Node)#8 (2) { [ "data" ]=> string(4) "aaa7" [ "next" ]=> object(Node)#7 (2) { [ "data" ]=> string(4) "aaa6" [ "next" ]=> object(Node)#6 (2) { [ "data" ]=> string(4) "aaa5" [ "next" ]=> object(Node)#5 (2) { [ "data" ]=> string(4) "aaa4" [ "next" ]=> object(Node)#4 (2) { [ "data" ]=> string(4) "aaa3" [ "next" ]=> object(Node)#3 (2) { [ "data" ]=> string(4) "aaa2" [ "next" ]=> object(Node)#2 (2) { [ "data" ]=> string(4) "aaa1" [ "next" ]=> NULL } } } } } } } } } } } object(Node)#12 (2) { [ "data" ]=> NULL [ "next" ]=> object(Node)#2 (2) { [ "data" ]=> string(4) "aaa1" [ "next" ]=> object(Node)#3 (2) { [ "data" ]=> string(4) "aaa2" [ "next" ]=> object(Node)#4 (2) { [ "data" ]=> string(4) "aaa3" [ "next" ]=> object(Node)#5 (2) { [ "data" ]=> string(4) "aaa4" [ "next" ]=> object(Node)#6 (2) { [ "data" ]=> string(4) "aaa5" [ "next" ]=> object(Node)#7 (2) { [ "data" ]=> string(4) "aaa6" [ "next" ]=> object(Node)#8 (2) { [ "data" ]=> string(4) "aaa7" [ "next" ]=> object(Node)#9 (2) { [ "data" ]=> string(4) "aaa8" [ "next" ]=> object(Node)#10 (2) { [ "data" ]=> string(4) "aaa9" [ "next" ]=> object(Node)#11 (2) { [ "data" ]=> string(5) "aaa10" [ "next" ]=> NULL } } } } } } } } } } } |