今天继续刷leetcode,第82题,移除有序链表中重复的元素。
分析:
设置两个指针,一个指向前一个,一个指向后面没有重复的那一个;
问题:
1、头部就是重复的;
2、尾部是重复的;
附上c++代码1:
/**
* 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||!head->next)
return head;
ListNode * newHead=new ListNode(0);
ListNode * temp=newHead;
while(head && head->next)
{
if(head->val==head->next->val)
{
while(head->next && head->next->val==head->val)
head=head->next;
head=head->next;
}
else
{
temp->next=head;
temp=temp->next;
head=head->next;
}
}
temp->next=head;
return newHead->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||!head->next)
return head;
ListNode * newHead=new ListNode(0);
newHead->next=head;
ListNode * pre=newHead;
while(pre->next)
{
ListNode *cur=pre->next;
while(cur->next && cur->val==cur->next->val)
cur=cur->next;
if(cur!=pre->next)
pre->next=cur->next;
else
pre=pre->next;
}
return newHead->next;
}
};
附上python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
newhead=ListNode(0)
temp=newhead
while head and head.next:
if head.val==head.next.val:
while head.next and head.next.val==head.val:
head=head.next
head=head.next
else:
temp.next=head
temp=temp.next
head=head.next
temp.next=head
return newhead.next