题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
解释:
删除重复的数字重复的部分,使得每个元素值出现一次,注意只是删除重复的部分,不是把重复的数字都删掉。所以直接遍历一遍就好了,头结点是不会变化的,本系列的II的要求是删除所有重复的数字,和本题的解法是不一样的。
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
"""
cur=head
while cur:
while cur.next and cur.next.val==cur.val:
cur.next=cur.next.next
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) {
ListNode* cur=head;
while (cur)
{
while(cur->next &&cur->next->val==cur->val)
{
cur->next=cur->next->next;
}
cur=cur->next;
}
return head;
}
};
总结:
这题目看似简单,但是还是要注意循环判断条件的,比如刚开始的while(cur)
。