1. Remove Duplicates from Sorted List
题目要求:
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
.
这道题不难。具体程序如下:
/**
* 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; int preVal = head->val;
ListNode *preNode = head;
ListNode *start = head->next;
while(start)
{
while(start && start->val == preNode->val)
{
ListNode *next = start->next;
preNode->next = next;
delete start;
start = next;
} if(!start)
break; preNode = start;
start = start->next;
} return head;
}
};
2. 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
.
该题可以通过添加dummy节点以方便编程。具体程序如下:
/**
* 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; int preVal = head->val;
ListNode *dummy = new ListNode();
dummy->next = head;
ListNode *prepreNode = dummy, *preNode = head;
ListNode *start = head->next;
while(start)
{
bool flag = true;
while(start && start->val == preNode->val)
{
flag = false;
ListNode *next = start->next;
preNode->next = next;
delete start;
start = next;
} if(flag)
{
prepreNode = preNode;
preNode = preNode->next;
}
else
{
prepreNode->next = preNode->next;
delete preNode;
preNode = prepreNode->next;
} if(!preNode || !preNode->next)
break;
start = preNode->next;
} head = dummy->next;
delete dummy;
dummy = nullptr; return head;
}
};