题目连接:
删除有序链表中重复的元素-II_牛客题霸_牛客网 (nowcoder.com)
题目简介:
描述
给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
例如:
给出的链表为1→2→3→3→4→4→5 , 返回1→2→5
给出的链表为1→1→1→2→3 , 返回2→3
数据范围:链表长度 0≤n≤10000,链表中的值满足 ∣val∣≤1000
要求:空间复杂度 O(n),时间复杂度 O(n)
进阶:空间复杂度 O(1),时间复杂度 O(n)
题目解法:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
BM15 删除有序链表中重复的元素-II
描述
给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
例如:
给出的链表为1→2→3→3→4→4→5, 返回1→2→5.
给出的链表为1→1→1→2→3, 返回2→3.
数据范围:链表长度 0≤n≤10000,链表中的值满足 ∣val∣≤1000
要求:空间复杂度 O(n),时间复杂度 O(n)
进阶:空间复杂度 O(1),时间复杂度 O(n)
*/
struct ListNode {
int val;
struct ListNode *next;
};
//这道题写的逻辑很混乱,为了过而过,加了很多条件和reture出口
struct ListNode* deleteDuplicates1(struct ListNode* head ) {
// write code here
struct ListNode* dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* dummyCur = dummyHead;
struct ListNode* cur = head;
struct ListNode* tmp;
int RepFlag = 0; //重复标志位
if(!cur || !cur->next)return head; //
tmp = cur->next;
while(cur){
if(tmp && cur->val == tmp->val){
tmp = tmp->next;
if(!tmp) break;
RepFlag = 1;
continue;
}else if(!tmp || RepFlag == 0){
dummyCur->next = cur;
dummyCur = dummyCur->next;
cur = cur->next;
if(!cur){
break;
}
tmp = cur->next;
if(!tmp){
dummyCur->next = cur;
return dummyHead->next;
}
}
if(RepFlag){
RepFlag = 0;
cur = tmp;
if(!cur) break;
tmp = cur->next;
continue;
}
}
dummyCur->next = NULL;
return dummyHead->next;
}
struct ListNode* deleteDuplicates(struct ListNode* head ) {
// write code here
struct ListNode* dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* pre, *cur, *next;
dummyHead->next = head;
pre = dummyHead, cur = head, next = head->next;
if(!cur || !next) return head;
while(next){ //如果next节点没到末尾,继续循环 dummy(p)-1(c)-1(n)-2-2-NULL
if(cur->val != next->val){ //如果cur与next的值相等,三个指针一起移动 dummy(p)-1(c)-1(n)-2-2-NULL
pre = cur;
cur = next;
next = next->next;
}else{ //如果cur与next的值不相等
while(next->next && next->val == next->next->val) //将next移到最后一个 dummy(p)-1(c)-1(n)-2-2-NULL
next = next->next;
if(!next->next){ //如果next的下一个为空即 dummy(p)-1(c)-1(n)-NULL
pre->next = NULL; //dummy(p)-NULL
return dummyHead->next;
}
cur = next->next; //如果next的下一个不为空, dummy(p)-1 -1(c/n)-2-2-NULL
next = cur->next; //dummy(p)-1 -1(c)-2(n)-2-NULL
pre->next = cur; //dummy(p) -1(c)-2(n)-2-NULL
}
}
return dummyHead->next;
}
void buildList(struct ListNode* head, int * input, int n){
for(int i=0; i<n; i++){
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = input[i];
head = head->next;
head->next = NULL;
head->val = 0;
}
}
/**************************end******************************************/
int main ()
{
int input1[]={1,1};
struct ListNode LNa, LNb;
buildList(&LNa, input1, sizeof(input1)/sizeof(int));
struct ListNode* ret = deleteDuplicates(&LNa);
printf("\r\nret:");
while(ret){
printf("%d->", ret->val);
ret = ret->next;
}
return 0;
}