給出一個排好序的連結清單,删除連結清單中的所有重複出現的元素,隻保留原連結清單中隻出現一次的元素。
例如:
給出的連結清單為1->2->3->3->4->4->5, 傳回1->2->5.
給出的連結清單為1->1->1->2->3, 傳回2->3.
思路:這個主要是頭結點怎麼處理
<?php
class Node {
public $next = null;
public $val;
public function __construct($val) {
$this->val = $val;
}
}
function deleteDuplicates($head) {
//先要找一個新的頭節點,友善找到下一個頭結點
$newHead = new Node($head->val - 1);
$newHead->next = $head;
$node = $newHead;
$pre = $newHead;//用來記錄前一個節點
while ($node != null) {
if ($node->val == $node->next->val) {
$node1 = $node->next;
while ( $node1 != null && $node1->val == $node->val) {
$node1 = $node1->next;
}
$pre->next = $node1;
$node = $node1;
continue;
}
$pre = $node;
$node = $node->next;
}
return $newHead->next;
}
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(2);
$node4 = new Node(2);
$node5 = new Node(3);
$node6 = new Node(3);
$node7 = new Node(4);
$node1->next = $node2;
$node2->next = $node3;
$node3->next = $node4;
$node4->next = $node5;
$node5->next = $node6;
$node6->next = $node7;
$ret = deleteDuplicates($node1);
while ($ret != null) {
print $ret->val . "\n";
$ret = $ret->next;
}