在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。 例如,鍊錶1->2->3->3->4->4->5 處理後為 1->2->5
整體需要考慮第乙個數字和第二個數字相同的情況,這種情況要設立乙個新的頭節點,放置於鍊錶的首部
class listnode:
def __init__(self,x):
self.val=x
self.next=none
class solution:
def deleteduplication(self, phead):
# write code here
if phead == none and phead.next == none:#不加and phead.next == none反而能完全通過,加上90%,費解
return phead
first = listnode(-1)
first.next = phead#避免第乙個和第二個數重複
pre = first
last = phead#last指標相當於工作指標
while last:
if last.next != none and last.val == last.next.val:
val = last.val
last = last.next
while last.next != none and val == last.next.val:
last = last.next
pre.next = last.next
last = last.next
else:
pre = pre.next
last = last.next
return first.next#一定要返回這個,因為first位置是永遠不變的,phead可能都已經被刪掉了
#測試用例
if __name__ == '__main__':
list1=listnode(1)
list1.next=listnode(1)
list1.next.next=listnode(3)
list1.next.next.next=listnode(3)
list1.next.next.next.next=listnode(3)
list1.next.next.next.next.next=listnode(4)
list1.next.next.next.next.next.next=listnode(5)
answer=solution()
q=answer.deleteduplication(list1)
if q == none:
print("沒有")
else:
while q:
print(q.val,'\n')
q = q.next
鍊錶 刪除鍊錶中重複的節點
刪除鍊錶中重複的節點 方法一 採用遞迴的方法,但這種方法在鍊錶無重複節點時效率不高 function deleteduplication phead if phead.val phead.next.val return deleteduplication node 採用遞迴的方法從下乙個不重複的點開...
鍊錶 刪除鍊錶中重複的節點
刪除鍊錶中重複的節點 方法一 採用遞迴的方法,但這種方法在鍊錶無重複節點時效率不高 function deleteduplication phead if phead.val phead.next.val return deleteduplication node 採用遞迴的方法從下乙個不重複的點開...
刪除鍊錶中重複的節點
題目描述 在乙個排序的鍊錶中,存在重複的結點,請刪除該鍊錶中重複的結點,重複的結點不保留,返回煉表頭指標。例如,鍊錶1 2 3 3 4 4 5 處理後為 1 2 5 這個題目首先考慮到頭結點也可能是重複的節點,所以需要設定乙個頭結點之前的節點。之後需要3個指標 pre,cur和next struct...