>  기사  >  백엔드 개발  >  단일 연결 목록 뒤집기 작업의 PHP 구현 예

단일 연결 목록 뒤집기 작업의 PHP 구현 예

小云云
小云云원래의
2017-12-09 10:06:371634검색

시퀀스에 후속 노드를 가리키는 링크만 포함된 경우 연결된 목록을 단일 연결 목록이라고 합니다. 이 글은 주로 PHP에서 단일 연결 리스트 뒤집기 연산의 구현을 소개하고, PHP 단일 연결 리스트의 정의, 순회, 재귀, 뒤집기 및 기타 관련 연산 기술을 분석하여 필요한 친구들이 참고할 수 있습니다. 모든 사람에게 도움이 되기를 바랍니다.

단일 연결 리스트의 정의와 반전 연산 방법은 다음과 같습니다:

<?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().&#39; &#39;;
    $tmpHead = $tmpHead->getNext();
  }
  echo "\n";
  //$head = reverse($head);
  $head = reverse2($head);
  while($head != null){
    echo $head->getValue().&#39; &#39;;
    $head = $head->getNext();
  }
}
test();
?>

연산 결과:

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


관련 권장 사항:
단일 연결 목록의 Python 구현

PHP 단일 연결 목록 뒤집기

php 코드 PHP 단일 연결 목록 구현 코드

위 내용은 단일 연결 목록 뒤집기 작업의 PHP 구현 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.