题目:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
思路:
1、定义一个头结点。遍历链表,如果当前节点存在,并且当前节点的下一节点存在并且相等,则将其继续往后循环,直至找到节点值不相等的下一节点,否则就保留当前节点值的结果
Python代码:
# 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):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
ret = ListNode(0)
guard = ret
while head and head.next:
if head.val == head.next.val:
while head.next and head.val == head.next.val:
head = head.next
ret.next = head.next
else:
ret.next = head
ret = ret.next
head = head.next
return guard.next
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) {
if (head==nullptr || head->next==nullptr){
return head;
}
ListNode* ret = new ListNode(0);
ListNode* guard = ret;
while (head!=nullptr && head->next!=nullptr){
if (head->val == head->next->val){
while (head->next!=nullptr && head->val == head->next->val){
head = head->next;
}
ret->next = head->next;
}else{
ret->next = head;
ret = ret->next;
}
head = head->next;
}
return guard->next;
}
};