• python链表2


    class Node:
        def __init__(self, value=None, next=None):
            self.value = value
            self.next = next
    
    
    class LinkedList(object):
    
        def __init__(self):
            # 初始化链表时, 创建一个head节点,该节点的value和next都为None
            # head的value值是啥无所谓
            # 注意, 不要把链表的head节点和head节点指向的下一个节点看着是一个节点
            # head.next 才是链表的第一个节点
            # head是链表的一个属性
            # 遍历链表时都是从 head.next 开始的
            node = Node()
            self.head = node
    
        # 头插法, 在链表的头部插入一个新的节点
        def add_first(self, value):
            node = Node(value)
            node.next = self.head.next  # 把第一个节点self.head.next,作为新节点的next
            self.head.next = node  # 第一个节点为新节点, head指向新节点
    
        # 在尾部添加一个元素
        def add_last(self, value):
            node = Node(value)
            # 空链表
            if self.head.next is None:
                self.head.next = node
            # 非空链表
            else:
                # 从第一个节点开始遍历, 直到最后一个节点
                current = self.head.next
                while current.next: # 注意这里是current.next,因为后面使用了current.next
                    current = current.next
                current.next = node
    
        def remove_first(self):
            self.head.next = self.head.next.next
    
        def __str__(self):
            current = self.head.next
            while current:
                print(current.value, end='	')
                current = current.next
            return ''
    
    
    def merge_sort_linked_list(l1, l2):
        dummy = cur = Node()
        while l1 and l2:
            if l1.value < l2.value:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next= l1 or l2
        return dummy.next
  • 相关阅读:
    今日进度
    今日进度
    今日进度
    今日进度
    今日进度
    每周总结
    今日进度
    python设置环境变量
    Python Property属性【python风格】
    学习-robot【字符串汇总】
  • 原文地址:https://www.cnblogs.com/yaoqingzhuan/p/12791773.html
Copyright © 2020-2023  润新知