面試題18:刪除鏈表節點
阿新 • • 發佈:2018-12-23
ext strong 頭指針 存在 節點 表頭 head dup node
18.1 在 O(1) 時間內刪除鏈表節點
<?php header("content-type:text/html;charset=utf-8"); /* * 在 O(1) 時間內刪除鏈表節點。 P119 */ class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } } function deleteNode($head,$deleteNode){ if($head == null || $deleteNode== null){ return false; } if($head->next == null){ return null; } if($deleteNode->next == null){ return traverseDelete($head); } else{ $deleteNode->val = $deleteNode->next->val; $deleteNode->next = $deleteNode->next->next; return $head; } } function traverseDelete($head){ $cur = $head; while ($cur->next->next != null){ $cur = $cur->next; } $cur->next = null; 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); $deleteNode = $head->next->next->next->next; print_r(deleteNode($head,$deleteNode));
18.2 刪除鏈表中重復的結點
<?php header("content-type:text/html;charset=utf-8"); /* * 在一個排序的鏈表中,存在重復的結點,請刪除該鏈表中重復的結點,重復的結點不保留,返回鏈表頭指針。 * 例如,鏈表1->2->3->3->4->4->5 處理後為 1->2->5。P122 */ class ListNode{ var $val; var $next = NULL; function __construct($x){ $this->val = $x; } } function deleteDuplication($pHead) { if($pHead == null || $pHead->next == null){ return $pHead; } $next = $pHead->next; if($pHead->val == $next->val){ //若頭結點與相鄰的節點相等,就一直向下遍歷到不等的地方,此時next就指向不等的結點 while ($next != null && $pHead->val == $next->val){ $next = $next->next; } return deleteDuplication($next); //以該不等的結點為頭,繼續向下遍歷 } else{ $pHead->next = deleteDuplication($pHead->next);//若頭結點與相鄰的節點不等,那就看下一個結點。 } return $pHead; } $head = new ListNode(1); $head->next = new ListNode(1); $head->next->next = new ListNode(2); $head->next->next->next = new ListNode(3); $head->next->next->next->next = new ListNode(3); $head->next->next->next->next->next = new ListNode(4); $head->next->next->next->next->next->next = new ListNode(5); print_r(deleteDuplication($head));
面試題18:刪除鏈表節點