zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):链表类:第83题:删除排序链表中的重复元素:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

    题目:
    删除排序链表中的重复元素:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
    思路:
    双指针法。
    程序1:暴力法,超时了
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
     
    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            if not head:
                return None
            myNode = head
            while myNode and myNode.next:
                if myNode.val == myNode.next.val:
                    myNode.next = head.next.next
                else:
                    myNode = myNode.next
            return head
    程序2:双指针
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None

    class Solution:
        def deleteDuplicates(self, head: ListNode) -> ListNode:
            if not head:
                return None
            if not head.next:
                return head
            index1 = head
            index2 = head.next
            while index2:
                if index1.val == index2.val:
                    index2 = index2.next
                elif index1.val != index2.val:
                    index1.next = index2
                    index1 = index1.next
                    index2 = index2.next
            index1.next = None
            return head
  • 相关阅读:
    【转】以太坊分片:Overview and Finality
    Raiden Network — Ethereum 区块链支付通道
    ERC 和 EIP 代表什么呢?
    【转】什么是加密经济学
    Ethereum Probabilistic Micropayments
    【转】以太坊钱包分析与介绍
    【转】用Python从零开始创建区块链
    【转】用 Go 构建一个区块链
    通用权限管理系统组件 (GPM
    通用权限管理系统组件 (GPM
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12813371.html
Copyright © 2011-2022 走看看