leetcode83.Remove Duplicates from Sorted List

题目要求

1
2
从有序链表中删除重复的数字,并且返回删除后的头结点
例如输入链表为1->1->2,返回1->2

这题和leetcode26相似,只是数据结构从数组变成了链表

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
29
30
31
32
33
/**
* @author rale
*
* 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.
*/
public class RemoveDuplicatesfromSortedList {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return head;
}
ListNode result = new ListNode(-1);
result.next = head;
while(head.next!=null){
if(head.next.val==head.val){
head.next = head.next.next;
}else{
head = head.next;
}

}
return result.next;
}

public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}

若还有更好的思路,请多多指教!