程式設計13 刪除鍊錶的中間結點和a b處的結點

2022-08-01 05:27:13 字數 1688 閱讀 5750

<?php 

header("content-type:text/html;charset=utf-8");

/**刪除鍊錶的中間結點和a/b處的結點 p38 */

class

node

}function removemidnode($head

)

elseif($head->next->next ==null

)

else

$pre->next = $pre->next->next

;

return

$head

; }

}function removebyratio($head,$a,$b

)

$length = 0;

$cur = $head

;

while ($cur != null

)

$ratio = ceil($a * $length / $b

);

if($ratio == 1)

if($ratio > 1)

$cur->next = $cur->next->next

; }

return

$head;}

$head1 = new node(1);

$head1->next = new node(3);

$head1->next->next = new node(5);

$head1->next->next->next = new node(7);

$head1->next->next->next->next = new node(9);

$head1->next->next->next->next->next = new node(11);

$head2 = new node(2);

$head2->next = new node(4);

$head2->next->next = new node(6);

$head2->next->next->next = new node(8);

$head2->next->next->next->next = new node(10);

$head2->next->next->next->next->next= new node(12);

echo "當前鍊錶為:";

echo "

";print_r($head1

);echo "

";echo "

";echo "刪除中間結點後的單鏈表為:";

echo "

";print_r(removemidnode($head1

));echo "

";echo "

";echo "當前鍊錶為:";

echo "

";print_r($head2

);echo "

";echo "

";echo "刪除2/3(第4個)結點後的單鏈表為:";

echo "

";print_r(removebyratio($head2,2,3));

輸出結果:

鍊錶的中間結點

題目 給定乙個帶有頭結點 head 的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點。示例 1 輸入 1,2,3,4,5 輸出 此列表中的結點 3 序列化形式 3,4,5 返回的結點值為 3 測評系統對該結點序列化表述是 3,4,5 注意,我們返回了乙個 listnode ...

鍊錶的中間結點

給定乙個帶有頭結點 head 的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點。示例 1 輸入 1,2,3,4,5 輸出 此列表中的結點 3 序列化形式 3,4,5 返回的結點值為 3 測評系統對該結點序列化表述是 3,4,5 注意,我們返回了乙個 listnode 型別的...

鍊錶的中間結點

力扣題目鏈結 給定乙個帶有頭結點 head 的非空單鏈表,返回鍊錶的中間結點。如果有兩個中間結點,則返回第二個中間結點。例項1 輸入 1,2,3,4,5 輸出 此列表中的結點 3 序列化形式 3,4,5 返回的結點值為 3 例項2 輸入 1,2,3,4,5,6 輸出 此列表中的結點 4 序列化形式 ...