一.题目
Remove Duplicates from Sorted List II
Total Accepted: 37833 Total Submissions: 151627My SubmissionsGiven a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这道题和Remove Duplicates from Sorted List类似,但是,这道题是将所有重复的节点都去掉,而另外一道题对于重复的元素值保留一个节点,因此,这道题可以在另外一道题的基础上进行修改。
对于将重复出现的节点都去掉,我们可以通过设置一个标记位来实现。这个标记位记录了某个节点的值是否在它前面的节点中出现,如果出现了,则舍弃该节点,这样就可以解决这个问题了。同样的,这道题也要考虑输入链表只有一个节点的情况,对于这种情况,直接返回输入链表即可。对于链表的最后一个元素,通过判断标记位来决定是否将其添加到输出链表的尾部。
三.实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
// only has a single element
if (head->next == NULL)
{
return new ListNode(head->val);
}
ListNode Header(10);
ListNode *Tail = &Header;
ListNode *Next = NULL;
bool IsDuplicates = false;
while(head->next != NULL)
{
Next = head->next;
if (head->val != Next->val)
{
if (!IsDuplicates)
{
Tail->next = new ListNode(head->val);
// update the tail
Tail = Tail->next;
}
IsDuplicates = false;
}
else
{
IsDuplicates = true;
}
head = Next;
}
if (!IsDuplicates)
{
Tail->next = new ListNode(head->val);
}
return Header.next;
}
};
四.体会
这道题对于算法的考察并不多,只要考察的还是链表遍历和编程技巧,以及边界条件的考虑,只要细心,都是可以做对的。
版权所有,欢迎转载,转载请注明出处,谢谢
