Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
1->1->2
, return 1->2
.
Given
1->1->2->3->3
, return 1->2->3
.以下是我用了不少的时间做出来的。感觉略啰嗦,但是思路清晰简单(把相同的重复的攥起来一起删掉)。
思路。
C++
/**
* 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;
} //如果链表为空或者只有一个元素,那么无需删除,直接返回原头结点的指针
else
{
int count = 1; //count用来记录相同元素的个数,如果最后统计相同的个数超过1,也就是2以上那么进行链表删除操作
ListNode* p = head; //将头结点赋给指针p
while(p != NULL)
{
int a = p -> val; //a为当前的节点的值
ListNode* pp = p -> next; //pp依次往下走,知道下一个元素与a不相等的时候
while(pp != NULL)
{
int b = pp -> val;
if(a == b)
{
count ++;
pp = pp -> next;
continue;
}
else //如果a != b 则跳出小循环
{
break;
}
}
if(count > 1) //在循环外,查看count的值,大于1则说明此时有相同的元素个数大于1,需要链表删除操作。
{
p -> next = pp;
count = 1; //count重置
}
p = p -> next; //大循环跳到下一个位置
}
return head;
}
}
};
精简的思路:
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* cur = head;
while(cur && cur -> next )
{
if(cur -> val == cur -> next -> val)
cur -> next = cur -> next -> next;
else
cur = cur -> next;
}
return head;
}
};
还是这个好一点!!good,学习。