Remove Duplicates from Sorted List
Given a sorted linked list, delete allduplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return1->2->3.
这题跟26RemoveDuplicates from Sorted Array题目一样,只是输入变成了链表的头指针。
首先需要一个指针作为返回,这题用链表的指针的话我们就不用维护新的指针了。一共2个指针。比数组输入的简单一些,也不能走交换思路了。
Leetcode的AcceptedSolutions Runtime Distribution
源码:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* deleteRule(ListNode* head);
ListNode* deleteDuplicates(ListNode* head);
int main()
{
ListNode l1(1);
ListNode* pl1 = &l1;
ListNode l2(2);
ListNode* pl2 = &l2;
ListNode l3(1);
ListNode* pl3 = &l3;
pl1->next = pl2;
cout << deleteDuplicates(pl1)->val;
return 0;
}
ListNode* deleteDuplicates(ListNode* head){
//////////////////////////////////////////////////
//leetcode 83
//Remove Duplicates from Sorted List
//////////////////////////////////////////////////
if (NULL == head) return NULL;
ListNode* res = head;
while (head->next)
{
if (head->val == head->next->val)
{
head->next = head->next->next;
}
else
{
head = head->next;
}
}
return res;
///////////////////////////////////////////////////
//leetcode 82
//Remove Duplicates from Sorted List ii
///////////////////////////////////////////////////
//return deleteRule(head);
}
ListNode* deleteRule(ListNode* head){
ListNode* res = head;
return res;
}
1270




被折叠的 条评论
为什么被折叠?



