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.
解题思路:与之前刷过的一题有所不同,这里要求保留重复的结点.这简单了很多,用双指针的方式遍历一遍链表,删除值相同结点即可.
#include<iostream>
#include<vector>
using namespace std;
//Definition for singly - linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *deleteDuplicates(ListNode *head) {
if (head == NULL)
return NULL;
ListNode*PreNode = head;
ListNode*CurNode = head;
while (CurNode->next!=NULL)//注意这边的条件
{
CurNode = CurNode->next;
if (CurNode->val!=PreNode->val){
PreNode->next = CurNode;
PreNode = CurNode;
}
}
PreNode->next = NULL;
return head;
}
本文介绍如何通过双指针法解决链表中删除重复元素的问题,包括算法思路、代码实现及实例解析。
728

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



