您的位置:首页 > 其它

Leetcode | Remove Duplicates from Sorted List I && II

2014-05-17 14:46 519 查看

Remove Duplicates from Sorted List I

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.

如果下一个节点和当前节点的值一样,就继续往后。这样找到的是重复数的最后一个。比如1->1->2;

当然也可以找到重复数的第一个数;

注意delete掉那些重复的点。

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head, *newH = NULL, *tail, *tmp;
while (p != NULL) {
while (p->next != NULL && p->next->val == p->val) {
tmp = p->next;
delete p;
p = tmp;
}
if (newH == NULL) {
newH = p;
} else {
tail->next = p;
}
tail = p;
p = p->next;
}
return newH;
}
};


Remove Duplicates from Sorted List II

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.

和Remove Duplicates from Sorted List I类似。加了一个判断是否重复数的条件。最后tail要指向NULL,因为原链表最后一个元素不一定会加进来。

这道题用c++很奇怪。下面的代码没有delete是可以accepted的。

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head, *newH = NULL, *tail, *current, *tmp;
while (p != NULL) {
current = p;
while (p->next != NULL && p->next->val == p->val) p = p->next;
if (p == current) {
if (newH == NULL) {
newH = p;
} else {
tail->next = p;
}
tail = p;
}
p = p->next;
}
if (tail) tail->next = NULL;
return newH;
}
};


但是加了delete的逻辑之后就runtime error了。这份代码应该是没有问题的。难道是leetcode自己有问题?

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head, *newH = NULL, *tail, *current, *tmp;
while (p != NULL) {
current = p;
while (p->next != NULL && p->next->val == p->val) {
tmp = p->next;
delete p;
p = tmp;
}
tmp = p->next;
if (p == current) {
if (newH == NULL) {
newH = p;
} else {
tail->next = p;
}
tail = p;
} else {
delete p;
}
p = tmp;
}
if (tail) tail->next = NULL;
return newH;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: