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
.
总算自己做出来一道了,虽然只是一道easy, 但好像连续几道都是看的答案。这道题确实简单吧,思路都很直接,注意一下循环条件就好了。(我是报错NullPointerException后自己加的curt.next != null && curt.val == curt.next.val. 入股不加上curt.next != null, 那么curt.next.val就会报空指针。)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curt = head;
while (curt != null && curt.next != null){
while (curt.next != null && curt.val == curt.next.val){
curt.next = curt.next.next;
}
curt = curt.next;
}
return dummy.next;
}
}