最基本的链表题目,需要注意的问题就是最后别忘了tail.next = null这样一回事…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode tail = new ListNode();
ListNode dummy = tail;
while(head != null) {
if(head.next == null || head.val != head.next.val) {
tail.next = head;
tail = tail.next;
}
while(head.next != null && head.val == head.next.val) {
head = head.next;
}
head = head.next;
}
tail.next = null;
return dummy.next;
}
}