PHP实现单链表翻转操作示例

2025-05-29 0 44

本文实例讲述了PHP实现单链表翻转操作。分享给大家供大家参考,具体如下:

当一个序列中只含有指向它的后继结点的链接时,就称该链表为单链表

这里给出了一个单链表的定义及翻转操作方法:

?

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
<?php

/**

* @file reverseLink.php

* @author showersun

* @date 2016/03/01 10:33:25

**/

class Node{

private $value;

private $next;

public function __construct($value=null){

$this->value = $value;

}

public function getValue(){

return $this->value;

}

public function setValue($value){

$this->value = $value;

}

public function getNext(){

return $this->next;

}

public function setNext($next){

$this->next = $next;

}

}

//遍历,将当前节点的下一个节点缓存后更改当前节点指针

function reverse($head){

if($head == null){

return $head;

}

$pre = $head;//注意:对象的赋值

$cur = $head->getNext();

$next = null;

while($cur != null){

$next = $cur->getNext();

$cur->setNext($pre);

$pre = $cur;

$cur = $next;

}

//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head

$head->setNext(null);

$head = $pre;

return $head;

}

//递归,在反转当前节点之前先反转后续节点

function reverse2($head){

if (null == $head || null == $head->getNext()) {

return $head;

}

$reversedHead = reverse2($head->getNext());

$head->getNext()->setNext($head);

$head->setNext(null);

return $reversedHead;

}

function test(){

$head = new Node(0);

$tmp = null;

$cur = null;

// 构造一个长度为10的链表,保存头节点对象head

for($i=1;$i<10;$i++){

$tmp = new Node($i);

if($i == 1){

$head->setNext($tmp);

}else{

$cur->setNext($tmp);

}

$cur = $tmp;

}

//print_r($head);exit;

$tmpHead = $head;

while($tmpHead != null){

echo $tmpHead->getValue().' ';

$tmpHead = $tmpHead->getNext();

}

echo "\\n";

//$head = reverse($head);

$head = reverse2($head);

while($head != null){

echo $head->getValue().' ';

$head = $head->getNext();

}

}

test();

?>

运行结果:

?

1
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0

希望本文所述对大家PHP程序设计有所帮助。

原文链接:http://blog.csdn.net/u013474436/article/details/50773736

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP实现单链表翻转操作示例 https://www.kuaiidc.com/93202.html

相关文章

猜你喜欢
发表评论
暂无评论