찾다
백엔드 개발PHP 튜토리얼PHP 이중 연결 목록 정의 및 사용 예 PHP 기술

PHP 이중 연결 목록 정의 및 사용 예 PHP 기술

Jun 28, 2018 pm 05:43 PM
php이중 연결리스트

이 글에서는 주로 PHP 이중 연결 목록의 정의와 사용법을 소개합니다. 이중 연결 목록 정의, 읽기, 삭제, 삽입 및 기타 관련 작업 기술을 캡슐화하기 위해 PHP에서 이중 연결 목록 클래스를 사용하는 방법이 필요한 친구들이 참고할 수 있습니다.

이 기사의 예에서는 PHP 양방향 링크 목록 링크 목록 정의 및 사용법에 대해 설명합니다. 참고하실 수 있도록 모두와 공유해 주세요. 자세한 내용은 다음과 같습니다.

한 세트의 데이터를 여러 번 이동해야 하므로 양방향 연결 목록이 작성됩니다. 하지만 저는 PHP에 대해 전혀 익숙하지 않습니다. 다양한 방법을 테스트하는 데에는 문제가 없지만 이러한 포인터와 PHP 언어의 깊은 수준에서 주의해야 할 점을 모르겠습니다. 모든 분들의 교육을 위해 게시하겠습니다. . 효율성은 테스트되지 않았습니다... 용서해주세요 ~

<?php
/**
 * **双向链表
 * @author zhiyuan12@
 */
/**
 * 链表元素结点类
 */
class Node_Element {
  public $pre = NULL; // 前驱
  public $next = NULL; // 后继
  public $key = NULL; // 元素键值
  public $data = NULL; // 结点值
  function __Construct($key, $data) {
    $this->key = $key;
    $this->data = $data;
  }
}
/**
 * 双向链表类
 */
class DoubleLinkedList {
  private $head; // 头指针
  private $tail; // 尾指针
  private $current; // 当前指针
  private $len; // 链表长度
  function __Construct() {
    $this->head = self::_getNode ( null, null );
    $this->curelement = $this->head;
    $this->tail = $this->head;
    $len = 0;
  }
  /**
   * @ desc: 读取链表全部结点
   */
  public function readAll() {
    $tmp = $this->head;
    while ( $tmp->next !== null ) {
      $tmp = $tmp->next;
      var_dump ( $tmp->key, $tmp->data );
    }
  }
  public function move($pos1, $pos2) {
    $pos1Node = $this->findPosition ( $pos1 );
    $pos2Node = $this->findPosition ( $pos2 );
    if ($pos1Node !== null && $pos2Node !== null) {
      $tmpKey = $pos1Node->key;
      $tmpData = $pos1Node->data;
      $pos1Node->key = $pos2Node->key;
      $pos1Node->data = $pos2Node->data;
      $pos2Node->key = $tmpKey;
      $pos2Node->data = $tmpData;
      return true;
    }
    return false;
  }
  /**
   * @ desc: 在指定关键词删除结点
   *
   * @param : $key
   *     指定位置的链表元素key
   */
  public function delete($key) {
    $pos = $this->find ( $key );
    if ($pos !== null) {
      $tmp = $pos;
      $last = null;
      $first = true;
      while ( $tmp->next !== null && $tmp->next->key === $key ) {
        $tmp = $tmp->next;
        if (! $first) {
          $this->delNode ( $last );
        } else {
          $first = false;
        }
        $last = $tmp;
      }
      if ($tmp->next !== null) {
        $pos->pre->next = $tmp->next;
        $tmp->next->pre = $pos->pre;
      } else {
        $pos->pre->next = null;
      }
      $this->delNode ( $pos );
      $this->delNode ( $tmp );
    }
  }
  /**
   * @ desc: 在指定位置删除结点
   *
   * @param : $key
   *     指定位置的链表元素key
   */
  public function deletePosition($pos) {
    $tmp = $this->findPosition ( $pos );
    if ($tmp === null) {
      return true;
    }
    if ($tmp === $this->getTail ()) {
      $tmp->pre->next = null;
      $this->delNode ( $tmp );
      return true;
    }
    $tmp->pre->next = $tmp->next;
    $tmp->next->pre = $tmp->pre;
    $this->delNode ( $tmp );
  }
  /**
   * @ desc: 在指定键值之前插入结点
   *
   * @param : $key
   *     //指定位置的链表元素key
   * @param : $data
   *     //要插入的链表元素数据
   * @param : $flag
   *     //是否顺序查找位置进行插入
   */
  public function insert($key, $data, $flag = true) {
    $newNode = self::_getNode ( $key, $data );
    $tmp = $this->find ( $key, $flag );
    if ($tmp !== null) {
      $newNode->pre = $tmp->pre;
      $newNode->next = $tmp;
      $tmp->pre = $newNode;
      $newNode->pre->next = $newNode;
    } else {
      $newNode->pre = $this->tail;
      $this->tail->next = $newNode;
      $this->tail = $newNode;
    }
    $this->len ++;
  }
  /**
   * @ desc: 在指定位置之前插入结点
   *
   * @param : $pos
   *     指定插入链表的位置
   * @param : $key
   *     指定位置的链表元素key
   * @param : $data
   *     要插入的链表元素数据
   */
  public function insertPosition($pos, $key, $data) {
    $newNode = self::_getNode ( $key, $data );
    $tmp = $this->findPosition ( $pos );
    if ($tmp !== null) {
      $newNode->pre = $tmp->pre;
      $newNode->next = $tmp;
      $tmp->pre = $newNode;
      $newNode->pre->next = $newNode;
    } else {
      $newNode->pre = $this->tail;
      $this->tail->next = $newNode;
      $this->tail = $newNode;
    }
    $this->len ++;
    return true;
  }
  /**
   * @ desc: 根据key值查询指定位置数据
   *
   * @param : $key
   *     //指定位置的链表元素key
   * @param : $flag
   *     //是否顺序查找
   */
  public function find($key, $flag = true) {
    if ($flag) {
      $tmp = $this->head;
      while ( $tmp->next !== null ) {
        $tmp = $tmp->next;
        if ($tmp->key === $key) {
          return $tmp;
        }
      }
    } else {
      $tmp = $this->getTail ();
      while ( $tmp->pre !== null ) {
        if ($tmp->key === $key) {
          return $tmp;
        }
        $tmp = $tmp->pre;
      }
    }
    return null;
  }
  /**
   * @ desc: 根据位置查询指定位置数据
   *
   * @param : $pos
   *     //指定位置的链表元素key
   */
  public function findPosition($pos) {
    if ($pos <= 0 || $pos > $this->len)
      return null;
    if ($pos < ($this->len / 2 + 1)) {
      $tmp = $this->head;
      $count = 0;
      while ( $tmp->next !== null ) {
        $tmp = $tmp->next;
        $count ++;
        if ($count === $pos) {
          return $tmp;
        }
      }
    } else {
      $tmp = $this->tail;
      $pos = $this->len - $pos + 1;
      $count = 1;
      while ( $tmp->pre !== null ) {
        if ($count === $pos) {
          return $tmp;
        }
        $tmp = $tmp->pre;
        $count ++;
      }
    }
    return null;
  }
  /**
   * @ desc: 返回链表头节点
   */
  public function getHead() {
    return $this->head->next;
  }
  /**
   * @ desc: 返回链表尾节点
   */
  public function getTail() {
    return $this->tail;
  }
  /**
   * @ desc: 查询链表节点个数
   */
  public function getLength() {
    return $this->len;
  }
  private static function _getNode($key, $data) {
    $newNode = new Node_Element ( $key, $data );
    if ($newNode === null) {
      echo "new node fail!";
    }
    return $newNode;
  }
  private function delNode($node) {
    unset ( $node );
    $this->len --;
  }
}
$myList = new DoubleLinkedList ();
$myList->insert ( 1, "test1" );
$myList->insert ( 2, "test2" );
$myList->insert ( "2b", "test2-b" );
$myList->insert ( 2, "test2-c" );
$myList->insert ( 3, "test3" );
$myList->insertPosition ( 5, "t", "testt" );
$myList->readAll ();
echo "+++";
$myList->deletePosition(0);
$myList->readAll ();
echo "..." . $myList->getLength ();
var_dump ( $myList->findPosition ( 3 )->data );
?>

실행 결과:

int(1)
string(5) "test1"
int(2)
string(7) "test2-c"
int(2)
string(5) "test2"
string(2) "2b"
string(7) "test2-b"
string(1) "t"
string(5) "testt"
int(3)
string(5) "test3"
+++int(1)
string(5) "test1"
int(2)
string(7) "test2-c"
int(2)
string(5) "test2"
string(2) "2b"
string(7) "test2-b"
string(1) "t"
string(5) "testt"
int(3)
string(5) "test3"
...6string(5) "test2"

관심을 가질 만한 기사:

PHP는 foreach를 사용하여 배열을 마법처럼 변환합니다( 예와 함께 설명) PHP 예제

PHP 큰따옴표에서 배열 요소에 액세스할 때 발생하는 오류 해결 방법 PHP Tips

php 1차원 배열에서 값 요소를 삭제하는 방법 PHP Tips

위 내용은 PHP 이중 연결 목록 정의 및 사용 예 PHP 기술의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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

TomakePhPapplicationSfaster, followthesesteps : 1) useopCodeCaching likeOpcachetOrpectipiledScriptBecode.2) MinimizedAtabaseQueriesByUsingQueryCachingandEfficientIndexing.3) leveragephp7 assistorBetterCodeeficiession.4) 구현 전략적 지시

PHP 성능 최적화 점검표 : 지금 속도를 향상시킵니다PHP 성능 최적화 점검표 : 지금 속도를 향상시킵니다May 12, 2025 am 12:07 AM

toImprovePhPapplicationSpeed, followthesesteps : 1) enableOpCodeCachingWithApcuTeCeScripteXecutionTime.2) 구현 구현

PHP 의존성 주입 : 코드 테스트 가능성을 향상시킵니다PHP 의존성 주입 : 코드 테스트 가능성을 향상시킵니다May 12, 2025 am 12:03 AM

의존성 주입 (DI)은 명시 적으로 전이적 종속성에 의해 PHP 코드의 테스트 가능성을 크게 향상시킵니다. 1) DI 디퍼 커플 링 클래스 및 특정 구현은 테스트 및 유지 보수를보다 유연하게 만듭니다. 2) 세 가지 유형 중에서, 생성자는 상태를 일관성있게 유지하기 위해 명시 적 표현 의존성을 주입합니다. 3) DI 컨테이너를 사용하여 복잡한 종속성을 관리하여 코드 품질 및 개발 효율성을 향상시킵니다.

PHP 성능 최적화 : 데이터베이스 쿼리 최적화PHP 성능 최적화 : 데이터베이스 쿼리 최적화May 12, 2025 am 12:02 AM

DatabaseQuesyOptimizationInphPinVolvesVesstoigiestoInsperferferferferformance.1) SelectOnlyNecessaryColumnstoredAtatatransfer.2) useinDexingTeSpeedUpdatarretieval.3) ubstractOrerEresultSoffRequeries.4) UtilizePreDstatements Offeffi

간단한 가이드 : PHP 스크립트와 함께 이메일 보내기간단한 가이드 : PHP 스크립트와 함께 이메일 보내기May 12, 2025 am 12:02 AM

phpisusedforendingemailsduetoitsbuitsbuitsbuit-inmail () functionandsupportivelibraries lifephpmailerandswiftmailer.1) usethemail () functionforbasicemails, butithaslimitations.2) EmployPhpmailerforAdvancedFeatirehtMailsAndAtachments.3))

PHP 성능 : 병목 현상 식별 및 수정PHP 성능 : 병목 현상 식별 및 수정May 11, 2025 am 12:13 AM

PHP 성능 병목 현상은 다음 단계를 통해 해결할 수 있습니다. 1) 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하여 문제를 찾으십시오. 2) 데이터베이스 쿼리 최적화 및 APCU와 같은 캐시 사용; 3) Array_Filter와 같은 효율적인 기능을 사용하여 배열 작업을 최적화합니다. 4) 바이트 코드 캐시에 대한 OpCache 구성; 5) HTTP 요청을 줄이고 사진 최적화와 같은 프론트 엔드 최적화; 6) 지속적으로 모니터링하고 성능을 최적화합니다. 이러한 방법을 통해 PHP 응용 프로그램의 성능을 크게 향상시킬 수 있습니다.

PHP의 종속성 주입 : 빠른 요약PHP의 종속성 주입 : 빠른 요약May 11, 2025 am 12:09 AM

종속성 주사 (di) inphpisadesignpattern thatmanages 및 enpleducesclassdelencies, 향상 codemodularity, trestability 및 maintainability .itallowspassingDepporsingDikedAbaseConnectionStoclassesAssparameters, 촉진 이용성.

PHP 성능 향상 : 캐싱 전략 및 기술PHP 성능 향상 : 캐싱 전략 및 기술May 11, 2025 am 12:08 AM

cachingimprovesphpperferferfermanceStoringResultsOfcomputationSorqueriesforquickRetrieval, retingServerloadandenhancancing responsetimestimes : 1) opcodecaching, opcodecaching, whitescompiledphps scriptsinmorytoskipcompileation; 2) dataCachingUsingmemmc

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)