题目:
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决思路:
判断当前和下一个元素是不是相同,如果相同,则抛弃,如果不同,移动cur指针到next.
解决方法:
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
我的写法:
public ListNode deleteDuplicates(ListNode head) {
ListNode dumpy = new ListNode(-1);
dumpy.next = head;
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
int x = cur.val;
while (cur.next != null && cur.next.val == x) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dumpy.next;
}
有点啰嗦了 写复杂了