码迷,mamicode.com
首页 > 编程语言 > 详细

python实现单链表

时间:2019-05-11 21:07:19      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:nod   复杂度   pre   时间   temp   color   bre   ==   rop   

class Chain():
    def __init__(self):
        self.first = None
        self.length = 0
    def is_empty(self):
        """是否为空"""
        return self.first == None
    def add(self, val):
        """头部添加"""
        node = Node(val)
        temp = self.first
        node.next = temp
        self.first = node
        self.length += 1
    def append(self, val):
        """尾部添加"""
        node = Node(val)
        if self.first:
            temp = self.first
            mid = None
            while temp:
                mid = temp
                temp = temp.next
            mid.next = node
        else:
            self.first = node
        self.length += 1
    def insert(self, item, val):
        """插入元素"""
        node = Node(val)
        temp, index = self.first, 0
        if item == 0:
            node.next, self.first = self.first, node
            self.length += 1
        else:
            while temp:
                if index+1 == item:
                    node.next, temp.next = temp.next, node
                    self.length += 1
                    break
                index += 1
                temp = temp.next
    def __len__(self):
        """链表长度"""
        return self.length
    @property
    def len_2(self):
        """链表长度(时间复杂度O(n))"""
        if not self.first:
            return 0
        else:
            temp = self.first
            length = 1
            while temp.next:
                length += 1
                temp = temp.next
            return length
    def pop(self):
        """删除尾部元素(有错误)"""
        temp = self.first
        mid = None
        while temp.next:
            mid, temp = temp, temp.next
        if mid:
            mid.next = None
            self.length -= 1
    def remove(self, item):
        """删除某一位置元素"""
        temp, index = self.first, 0
        if item == 0:
            if self.first:
                self.first = self.first.next
                self.length -= 1
        while temp:
            if index + 1 == item:
                temp.next = temp.next.next
                self.length -= 1
            index += 1
            temp = temp.next
    def bianli(self):
        """遍历链表"""
        temp = self.first
        while temp:
            print(temp.value)
            temp = temp.next
    def __iter__(self):
        pass
    def __next__(self):
        pass
class Node():
    def __init__(self, val):
        self.value = val
        self.next = None

 

python实现单链表

标签:nod   复杂度   pre   时间   temp   color   bre   ==   rop   

原文地址:https://www.cnblogs.com/jiaxiaoxin/p/10850008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!