题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:
是有两个循环判断的控制,上一个是主要对应2 - 3 - 4这种情况的,可以很快的把头指针移过来,下面这个循环是对应
存在相同值的,不断循环找下一个值。
参考答案:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if pHead is None or pHead.next is None:
return pHead
start = head = ListNode(-1)
head.next = pHead
while pHead and pHead.next:
if pHead.val == pHead.next.val:
val = pHead.val
while pHead and val == pHead.val:
pHead = pHead.next
start.next = pHead
else:
start = pHead
pHead = pHead.next
return head.next
思路二:
将链表里面所有的数存在一个列表里面,然后把列表里面只出现一次的数提取出来,在新建一个链表放进去。
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
res = []
while pHead:
res.append(pHead.val)
pHead = pHead.next
# filter函数和map相似,但是filter是返回布尔值去去输入列表进行判断
res = list(filter(lambda c: res.count(c) == 1, res))
newlist = ListNode(0)
pre = newlist
for i in res:
node = ListNode(i)
pre.next = node
pre = pre.next
return newlist.next
这种空间复杂度太高,不具备优势。
最后提供一个 C++ 版本,注意 C++ 中树节点创建过程!
C++ version:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == nullptr || pHead->next == nullptr){
return pHead;
}
ListNode* p1 = pHead;
ListNode* head = new ListNode(-1);
ListNode* node = head;
head->next = pHead;
int mark;
while(p1 != NULL && p1->next != NULL){
if(p1->val == p1->next->val){
mark = p1->val;
while(p1 && p1->val == mark){
p1 = p1->next;
}
node->next = p1;
}
else{
p1 = p1->next;
node = node->next;
}
}
return head->next;
}
};
Note
-
尤其注意Python下链表的创建,已经吃了无数次亏了;
-
这道题中,
while pHead and pHead.next:
与val = pHead.val while pHead and val == pHead.val: pHead = pHead.next start.next = pHead
都很值得学习。
-
filter函数和map相似,但是filter是返回布尔值去去输入列表进行判断,过滤掉计数为1的内容,返回计数>1的list结果:
# filter函数和map相似,但是filter是返回布尔值去去输入列表进行判断 res = list(filter(lambda c: res.count(c) == 1, res))
即:注意filter表达式的用法。
-
C++ 中树节点创建:
ListNode* head = new ListNode(-1);