leetcode:单链表之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.
即:给定一个链表,对链表进行滤重,使得每个数只出现一次。
c++实现:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode (int x):val(x),next(NULL){ }
};
ListNode *createListNode(int arr[],int n)
{
ListNode *r;
ListNode *p;
ListNode * L=(ListNode*)malloc(sizeof(ListNode));
r=L;
for(int i=0;i<n;i++)
{
p=(ListNode*)malloc(sizeof(ListNode));
p->val=arr[i];
r->next=p;
r=p;
}
r->next=NULL;
return L->next;
}
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL)
return head;
ListNode* p_cur = head;
ListNode* p_next = head->next;
while (p_cur != NULL && p_next != NULL)
{
if (p_cur->val == p_next-> val)
{
p_cur->next = p_next->next;
}
else
{
p_cur = p_cur->next;
}
p_next = p_next->next;
}
return head;
}
int main()
{
int a[]={1,1,2,3,3};
ListNode *input;
ListNode *out;
input= createListNode(a,5);
out=deleteDuplicates(input);
while(out != NULL)
{
cout<<out->val;
out = out->next;
}
cout<<endl;
return 0;
}
测试结果: