首页 > 代码库 > Remove Duplicates from Sorted List

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.

解题思路:与之前刷过的一题有所不同,这里要求保留重复的结点.这简单了很多,用双指针的方式遍历一遍链表,删除值相同结点即可.

#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;
}


Remove Duplicates from Sorted List