您的位置:首页 > 其它

<LeetCode> 题113:删除排序链表中的重复元素2

2016-07-26 14:03 591 查看

1. 题目描述:

给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。

例如:

给出 1->2->3->3->4->4->5->null,返回 1->2->5->null

给出 1->1->1->2->3->null,返回 2->3->null

2. 链表数据结构

/**
* struct ListNode
* {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
**/


3. 代码

3.1 思路1

class Solution
{
public:

ListNode * deleteDuplicates(ListNode *head)
{
if (head == NULL || head->next == NULL)
{
return NULL;
}

ListNode *newhead= new ListNode(0);
newhead->next = head;
ListNode *pre = newhead;

while (pre->next != NULL)
{
ListNode *cur = pre->next;

while (cur->next != NULL && cur->next->val == cur->val)
{
cur = cur->next;
}
if (cur != pre->next)
{
pre->next = cur->next;
}
else
{
pre = pre->next;
}
}
return newhead->next;
}
};


3.2 思路2:

遍历链表,记录相同数字的个数count,如果count=1,则保留,如果count>1,则删除。考虑到重复结点可能在链表表头,所以需要定义一个新的结点,然后连上原链表。

class Solution
{
public:

ListNode * deleteDuplicates(ListNode *head)
{
ListNode *newHead = new ListNode(0);
if(head == NULL || head->next == NULL)
{
return NULL;
}
ListNode *pre = newHead;
ListNode *cur = head;
while(head != NULL)
{
ListNode *p = head;
int count = 0;// 记录相同结点的个数
while(p != NULL && p->val == head->val)
{
p = p->next;
count++;
}
if(count == 1)  // count = 1, 说明就只有一个
{
pre->next = head;
pre = pre->next;
head = head->next;
}
else
head = p;
}
pre->next = NULL;// 断开后面的结点
return  newHead->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: