Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
給出1個排好序的鏈表,刪除所有的重復的數字,讓每一個元素只出現1次。
比如:
給出 1->1->2, 返回1->2.
給出1->1->2->3->3, 返回1->2->3.
既然鏈表本身已排好序了,那末只用比較當前位置的值和next的值是不是1樣,1樣就把next指向下1個再繼續判斷就行了,思路還是比較簡單,但是有幾個容易疏忽的點需要注意。
在自己檢測時可以試試代碼對下面幾個測試用例是不是能通過:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return head;
ListNode p = head;
while (p.next != null) {
ListNode q = p.next;
if (q.val == p.val) {
if (q.next != null) {
p.next = q.next;
}
else p.next = null;
}
else p = p.next;
}
return head;
}
}
版權所有:http://blog.csdn.net/cloudox_
上一篇 go profile
下一篇 c實現set集合