您的位置:首页 > 编程语言 > C语言/C++

[C++]Remove Duplicates from Sorted List 从已排序的链表中移除重复元素

2015-08-23 20:35 471 查看
leetcode 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

ps: 这也是前两天腾讯电面我的一道题,虽然思路对了,但是白板写的程序,把指针箭头引用写成(.)应用了,也不知道还有没有二面,/(ㄒoㄒ)/~~

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
.
简要翻译:题目的要求很简单就是给定一个已排序的单链表,要求删除链表中的重复元素。

实现代码:

<span style="font-size:14px;">#include <iostream>

using namespace std;

//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)
return NULL;
ListNode *p = head;
ListNode *temp = p->next;
while (p->next != NULL)
{
if (p->val == temp->val)
{
ListNode *tp = temp;
p->next = temp->next;
temp = p->next;
delete tp;
tp = NULL;
} else
{
p = p->next;
temp = p->next;
}
}
return head;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息