83.
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
去除重复的单链表节点。
时间12ms。
代码:
/**
* 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 != NULL) && ( cur->next != NULL ))
{
if(cur->val == cur->next->val)
cur->next = cur->next->next;
else
cur = cur->next;
}
return head;
}
};
82.
Given 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.
与上一题比,区别是要将所有重复的值全部删除。这样造成头结点的确定麻烦一些。
思路:
首先采用上一题的方法,将重复的节点大于一个的去掉,只剩下一个,并将重复节点值加入队列存储。
然后,从头到尾扫描,确定头结点。如果链表值与队列头部的值相同,则抛弃这个节点,队列头部出队列。直到队列为空或者链表节点值小于队列头部值为止,则找到头结点。
然后从头结点开始,将与队列值相同的节点去掉。
/**
* 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 == NULL || head->next == NULL)//排除基本情况
return head;
ListNode* cur = head;
ListNode* pre = NULL;
queue<int> a;
while( cur != NULL && cur->next != NULL )//先把重复数字存储在队列,然后根据队列从头到尾扫描,去除重复的值
{
if(cur->val == cur->next->val)
{
if(a.size() == 0 ||cur->val != a.back())
{
a.push(cur->val);
}
cur->next = cur->next->next;
}
else
cur = cur->next;
}
while(a.size() != 0 )//首先确定头指针
{
if(head->val == a.front())
{
head = head->next;
a.pop();
}
else
break;
}
cur = head;
while(a.size() != 0 )//去除重复的节点
{
if(cur->val < a.front())
{
pre = cur;
cur = cur->next;
}
else if( cur->val == a.front() )
{
pre->next = cur->next;
cur = cur->next;
a.pop();
}
}
return head;
}
};