您的位置:首页 > 理论基础 > 数据结构算法

LeetCode 83. Remove Duplicates from Sorted List

2016-03-10 10:28 651 查看
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语言实现

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *pre,*p;
if(head==NULL){
return head;
}
while(head!=NULL && head->next!=NULL && head->next->val==head->val){
head=head->next;
}
pre=head;
p=head->next;
while(p){
if(p->val==pre->val){
pre->next=p->next;
p=p->next;
}else{
pre=p;
p=p->next;
}
}
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息