给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if(head==NULL || head->next==NULL)
{
return head;
}
else
{
struct ListNode* p=head;
while(p!=NULL && p->next!=NULL)
{
if(p->val==p->next->val)
{
p->next=p->next->next;
}
else
{
p=p->next;
}
}
return head;
}
}
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
while head is None or head.next is None:
return head
else:
p=head
while p!=None and p.next!=None:
if p.val==p.next.val:
p.next=p.next.next
else:
p=p.next
return head