题目描述:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
解题思路1:
类似题解:面试题18. 删除链表的节点
代码1: 超出时间限制
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
pre, cur = head, head.next
while pre and cur:
if pre.val == cur.val:
pre.next = cur.next
else:
pre, cur = cur, cur.next
return head
解题思路2:
类似题解:面试题18. 删除链表的节点
代码2:
写法1:
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
res = head
while res and res.next:
if res.val == res.next.val:
res.next = res.next.next
else:
res = res.next
return head
写法2:
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
if not head: return None
pre, cur = head, head.next
while pre and cur:
if pre.val == cur.val:
pre.next = cur.next
cur = cur.next
else:
pre, cur = cur, cur.next
return head
C++写法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto cur = head;
while(cur){
if (cur -> next && cur -> next -> val == cur -> val)
cur -> next = cur -> next -> next;
else
cur = cur -> next;
}
return head;
}
};
参考链接:
题目来源:
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
同类题目:
[1]. 面试题18. 删除链表的节点
[2]. 237. 删除链表中的节点
[3]. 876. 链表的中间结点