Python数据结构——链表(一)单链表

之前学C时学到可以通过指针指向某一节点实现空间上不连贯的单位逻辑上连贯,也就是所谓的链表,Python中不存在指针的概念,可以通过定义类来实现类似链表的效果。

写下来做个总结

定义节点

class node(object):
    def __init__(self,item):
        self.item = item
        self.next = None

item代表存储的内容,next用来模拟指针。

创建单链表类

  • length:链表长度
  • head:链表头节点
  • count:现有节点数
class singlechainlist(object):
    def __init__(self,length:int):
        self.length = length
        self.head = node(None)
        self.count = 0
        
    def __num_node(self,x:int):
        self.count += x
    
    def search(self,x:node): # search for the node and return the precvious node
        if self.head.next == x:
            return self.head
        else:
            temp = self.head.next
            while temp.next != x:
                temp = temp.next
            return temp
        
    def add_node(self,node:node): # add at the end of chain
        if self.count == self.length:
            print('cannot exceed max length')
        else:
            self.find_tail().next = node
            self.__num_node(1)
            
    def find_tail(self,x=None): # find the last node
        if x is None:
            x = self.head
        if x.next is None:
            return x
        else:
            temp = x.next
            if temp.next is None:
                return temp
            else:
                return self.find_tail(temp)
    
    def del_node(self,x=None):
        if self.head.next is None:
            print('no node any more!')
        else:
            if x is None:
                self.search(self.find_tail()).next=None
                self.__num_node(-1)
            else:
                self.search(x).next = x.next
                x = None
                self.__num_node(-1)
    
    def insert_node(self,x:node,y:node):
        if self.count == self.length:
            print('cannot exceed max length')
        else:
            if self.head.next is None:
                self.head.next = y
                self.__num_node(1)
            else:
                self.search(x).next = y
                y.next = x
                self.__num_node(1)
            
    def get_chain(self):
        chain = [self.head]
        while chain[-1].next != None:
            chain.append(chain[-1].next)
        return chain

现在实现的功能:

  • 在末尾加节点
  • 在链表中插入节点
  • 查找节点
  • 删除节点
  • 获取完整链表

你可能感兴趣的:(Python数据结构——链表(一)单链表)