面試題22:鏈表中倒數第 K 個結點
阿新 • • 發佈:2018-12-30
const str find color func pid pri truct view
NowCoder
<?php header("content-type:text/html;charset=utf-8"); /* * 輸入一個鏈表,輸出該鏈表中倒數第k個結點。 P134 */ class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } } function FindKthToTail($head, $k) { if($head == null || $k ==0){ returnnull; } $count = 0; $cur = $head; while ($cur != null){ $cur = $cur->next; $count++; } if($count < $k){ return null; } for($i = 1;$i<=$count-$k;$i++){ $head = $head->next; } return $head; } $head = new ListNode(1);$head->next = new ListNode(2); $head->next->next = new ListNode(3); $head->next->next->next = new ListNode(4); $head->next->next->next->next = new ListNode(5); print_r(FindKthToTail($head,0));
面試題22:鏈表中倒數第 K 個結點