PHP反向链表

PHP反向链表


方法一:迭代

function reverseList($head) {
			
		  //第一种方法
		  $h = $head;//移动节点(后一个节点)
		  $n = null;//存储节点(前一个节点)
		    while($h != null){
		        $temp = $h->next; //存储 移动节点的指针(下一个节点的地址)
		        $h->next = $n;//移动节点的指针指向存储节点
		        $n = $h;//存储节点获得移动节点的地址
		        $h = $temp;//移动节点向后移动
		    }
		    return $n;

		  //第二种方法
		  $h = $head;
    	  $n = $head -> next;
          $head -> next = null;
		  while($n != null){
		        $temp = $n -> next; //存储后一个节点的地址
		        $n -> next = $h;//后一个节点的指针指向前面的节点
		        $h = $n;//前一个节点开始向后推
		        $n = $temp;//后一个节点开始向后推
		  }
          return $h;
}

方法二:递归

function reverseList($head) {

    if($head == null || $head -> next == null){
        return $head;
    }
    $p = reverseList($head ->next );
    $head->next->next = $head;
    $head -> next = null;
    return $p;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值