Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
方法一
分析:新建一个链表,用新的链表,来接收剔除相同数字后的链表,相当于把剔除后的链表插入到新的链表中。(不符合题目要求)
struct ListNode* deleteDuplicates_newList(struct ListNode* head)
{
if(!head) {
return NULL;
}
struct ListNode* headTemp = head;
struct ListNode* preListNodeTemp = NULL;
struct ListNode* rListNodeHead = NULL;
struct ListNode* rListNodepre = NULL;
struct ListNode* rListNodecur = NULL;
while(headTemp) {
preListNodeTemp = headTemp;
while(headTemp->next&&headTemp->val==headTemp->next->val) {
headTemp = headTemp->next;
}
if(preListNodeTemp != headTemp&&headTemp->val == preListNodeTemp->val) {
headTemp = headTemp->next;
}
if(preListNodeTemp == headTemp) {
/*头结点*/
if(rListNodeHead==NULL) {
rListNodeHead = (struct ListNode*)malloc(sizeof(struct ListNode));
rListNodepre = rListNodeHead;/*save the first linknode*/
rListNodeHead->next = NULL;/*set the linknode end*/
rListNodeHead->val = headTemp->val; /*set the value*/
}
else {
rListNodecur = (struct ListNode*)malloc(sizeof(struct ListNode));
rListNodepre->next = rListNodecur;/*insert the linknode*/
rListNodepre = rListNodepre->next;/*save the linknode*/
rListNodepre->next = NULL;/*set the linknode end*/
rListNodecur->val = headTemp->val;/*set the value*/
}
headTemp = headTemp->next;
}
}
return rListNodeHead;
}
方法二
题意要把链表中有重复的元素全部去除,只留下没有重复过的元素。
依旧是链表的操作,由于头节点也有可能删除,因此先建一个newListNodeHead节点头节点,方便原节点的删除。
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if(!head) {
return NULL;
}
struct ListNode* headTemp = head;
struct ListNode* freeListNodeTemp = NULL;
struct ListNode* preListNodeTemp = NULL;
/*1.creat a new Head*/
struct ListNode* newListNodeHead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* newListNodeHeadTemp = NULL;
newListNodeHead->next = NULL;
int valuePre = 0;
/*2.Find the first LinkNode*/
while(headTemp) {
preListNodeTemp = headTemp;
valuePre = preListNodeTemp->val;
while(headTemp->next&&headTemp->val==headTemp->next->val) {
freeListNodeTemp = headTemp;/*save the linknode to free*/
headTemp = headTemp->next;/*move to next linknode*/
free(freeListNodeTemp);/*free the linknode*/
}
if(preListNodeTemp != headTemp&&headTemp->val == valuePre) {
freeListNodeTemp = headTemp;/*save the linknode to free*/
headTemp = headTemp->next;/*move to next linknode*/
free(freeListNodeTemp);/*free the linknode*/
}
if(preListNodeTemp == headTemp) {
if(newListNodeHead->next==NULL) {
newListNodeHeadTemp = headTemp;
newListNodeHead->next = newListNodeHeadTemp;
}
else {
newListNodeHeadTemp->next = headTemp;
newListNodeHeadTemp = newListNodeHeadTemp->next;
}
headTemp = headTemp->next;
}
}
if(newListNodeHeadTemp!=NULL) {
newListNodeHeadTemp->next = NULL;
}
head = newListNodeHead->next;
free(newListNodeHead);
return head;
}
再向前移动pre和now指针。