. A linked list is a list with linked objects, 관계가있는 개체 목록이 아닙니다. 기본적으로 두 컨테이너 중 최악의 상황입니다. 그 구조를 다른 데이터 컨테이너로 변환하려고합니다. 실제 링크 된 목록은 데이터를 정렬하는 데 필요한 방식으로 정렬 될 필요가 없습니다.
좋은 방법은 이와 비슷한 것이 될 것입니다. 목록의 중간에 개체를 삽입하는 방법을 여러분에게 남겨 드릴 것입니다. 그리 어렵지 않습니다. 자신에게 부탁을,
<?php
function find_row($array, $id)
{
foreach($array as $current_row)
{
if($current_row['id'] === $id)
return $current_row;
}
return null;
}
function what_the_heck_sort($array)
{
$start_record = $array[0];
$working_record = $array[0];
$result = array($working_record);
while($working_record['prev'] !== null)
{
$working_record = find_row($array, $working_record['prev']);
array_unshift($result, $working_record);
}
$working_record = $start_record;
while($working_record['next'] !== null)
{
$working_record = find_row($array, $working_record['next']);
array_push($result, $working_record);
}
return $result;
}
// the test code
$test = array(
array("foo 01", 'id' => 0, 'prev' => null, 'next' => 1),
array("foo 02", 'id' => 1, 'prev' => 0, 'next' => 2),
array("foo 03", 'id' => 2, 'prev' => 1, 'next' => 3),
array("foo 04", 'id' => 3, 'prev' => 2, 'next' => 4),
array("foo 05", 'id' => 4, 'prev' => 3, 'next' => 5),
array("foo 06", 'id' => 5, 'prev' => 4, 'next' => 6),
array("foo 07", 'id' => 6, 'prev' => 5, 'next' => 7),
array("foo 08", 'id' => 7, 'prev' => 6, 'next' => 8),
array("foo 09", 'id' => 8, 'prev' => 7, 'next' => 9),
array("foo 10", 'id' => 9, 'prev' => 8, 'next' => null));
shuffle($test);
print_r(what_the_heck_sort($test));
?>
하지만 실제로는, 그리고 실제 작업을 수행합니다 일부 오컬트 이유 당신이 정말로, 정말로 배열을 필요로하는 경우
<?php
class LinkedObject
{
var $value;
var $prev;
var $next;
public function __construct($value, $prev = null, $next = null)
{
$this->value = $value;
$this->prev = $prev;
$this->next = $next;
}
public function append(LinkedObject $insertee)
{
$link = $this;
while($link->next != null)
$link = $link->next;
$link->next = $insertee;
$insertee->prev = $link;
}
public function __toString()
{
$str = $this->value;
if($this->next != null)
{
$str .= " » ";
$str .= $this->next;
}
return $str;
}
}
$head = new LinkedObject("foo");
$head->append(new LinkedObject("bar"));
$head->append(new LinkedObject("baz"));
echo $head . "\n"; // gives "foo » bar » baz"
?>
하지만, 여기 당신이 필요로하는 것이 무엇인가 개체가 아니라 배열을 사용하여 연결된 목록. 위의 정렬 방법은 제 생각에 제약 조건을 잘 알고 있지만,
은 어색하게 느립니다.은 각 ID에 대한 배열을 조회해야하기 때문입니다.
작동합니다? – Dolph
다음은 더 나은 샘플 코드가 필요하다고 생각합니다. –
왜 _arrays_를 사용하여 링크 된 목록을 구현하고 있습니까? 제게 아무런 이유없이 많은 문제가 생기는 것 같습니다. 단순히 객체를 사용하여 동일하게 구현할 수있을 때입니다. – zneak