【劍指offer】23—刪除鏈表中的重複節點

題目描述

在一個排序的鏈表中,存在重複的結點,請刪除該鏈表中重複的結點,重複的結點不保留,返回鏈表頭指針。 例如,鏈表1->2->3->3->4->4->5 處理後爲 1->2->5

方法一

在遍歷的時候,記錄上一個不重複的節點pPre,當前節點pThis,下個節點pNext。

在遍歷pThis的時候如果當前節點pThis的值跟後面的幾個節點數值相同,需要找到下個不同的節點,刪除重複節點,更新pPre和pThis;

如果前節點pThis的值跟後面的節點數值不同,直接更新pPre和pThis。

如果pHead就是重複的,需要更新pHead。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        # write code here
        if pHead == None or pHead.next == None:
            return pHead
        pPre = None
        pThis = pHead
        pNext = None
        while(pThis):
            # 當前節點和當前節點的next值相等,則循環
            if(pThis.next and pThis.next.val == pThis.val):
                pNext = pThis.next   # PNext指向當前節點的下一個節點

                #判斷是否下下一個節點仍然與當前節點的值相等
                while(pNext.next and pNext.next.val == pThis.val):
                    pNext = pNext.next  #重複元素序列中的後一個

                if(pThis == pHead):
                    pHead = pNext.next
                else:
                    pPre.next = pNext.next
                pThis = pNext.next #跳過重複元素

            else:
                # 不相等,則指向下個節點
                pPre = pThis
                pThis = pThis.next
        return pHead

方法二

構建一個新的鏈表,存儲不重複的節點。

class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if not pHead:
            return None
        a_list = []
        while pHead:
            a_list.append(pHead.val)
            pHead = pHead.next
        new_list = [i for i in a_list if a_list.count(i)==1]
        if new_list:
            root = pHead = ListNode(new_list[0])
            for i in range(1,len(new_list)):
                pHead.next = ListNode(new_list[i])
                pHead = pHead.next
            return root
        else:
            return None

方法三

鏈接:https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef?answerType=1&f=discussion
來源:牛客網

def deleteDuplication(self, pHead):
    # write code here
    if not pHead:
        return pHead
    #爲了防止頭結點是重複的,定義一個新結點指向頭結點
    temp = ListNode(0)
    temp.next = pHead
    pre, nex = temp, pHead
    while nex:
        if nex.next and nex.next.val == nex.val:
            #如果出現了和當前節點相同的值的時候,當前節點前移一位
            while nex.next and nex.next.val == nex.val:
                nex = nex.next
            pre.next = nex.next#只是指向,並沒有動pre,相當於刪除
            nex = nex.next
        else:
            pre = pre.next
            nex = nex.next
    return temp.next
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章