剑指offer-删除链表中重复的结点-链表-python ***

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

 思路:

如果该链表当前节点与下一节点为空,则返回前当前节点。

否则,比较这两个节点的val,使用递归,

如果 当两节点值相等时,使用temp来替代 pHead.next

然后循环判断temp是否为空,若不为空,则temp指向下一节点。

如果不相等,则移动到下一节点

# -*- 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 not pHead or not pHead.next:
            return pHead
        if pHead.val == pHead.next.val:
            temp = pHead.next
            while temp and temp.val == pHead.val:
                temp = temp.next
            return self.deleteDuplication(temp)
        else:
            pHead.next = self.deleteDuplication(pHead.next)
            return pHead

 

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        thead = ListNode('a')
        thead.next = head
        pre,cur = None,thead
        while cur:
            pre=cur
            cur=cur.next
            while cur and cur.next and cur.next.val == cur.val:
                t=cur.val
                while cur and cur.val==t:
                    cur=cur.next
            pre.next=cur
        return thead.next

 

posted @ 2019-12-10 09:37  ayew  阅读(162)  评论(0编辑  收藏  举报