zoukankan      html  css  js  c++  java
  • 剑指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
  • 相关阅读:
    文本框样式
    flash载入xml不显示中文之谜
    日期 时间 正则表达式
    .NET对象生命周期小结
    Python标准库12 数学与随机数 (math包,random包)
    CXF 4 应用开发
    CXF 2
    CXF 3
    MyEclipse提示键配置、提示快捷键、提示背景色、关键字颜色、代码显示
    CXF 5参考资料
  • 原文地址:https://www.cnblogs.com/ansang/p/12014802.html
Copyright © 2011-2022 走看看