python 实现链表

# -*- coding:utf-8 -*-
# auther="金木水火"
#链表
'''
1. 链表两个域,值+指针
2. 指针存放下一个节点的位置
3. 变量p指向表头
4. 最后一个节点指向None
5. 后进先出
'''
class node():
    #定义第一个节点
    def __init__(self,iterm=None):
        self.iterm=iterm
        self.next=None
class simpleLink():
    '''简单链表'''
    def __init__(self,node=None):
        self.__head=node
    def is_empty(self):
        if self.__head is None:
            print('链表为空')
    def add(self,iterm):
        n=node(iterm)
        n.next=self.__head
        self.__head=n

    def select(self):
        cur=self.__head
        while cur != None:
            print(cur.iterm)
            cur=cur.next

class DoubleNode():
    def __init__(self,iterm=None):
        self.iterm = iterm
        self.next = None
        self.prev =None
class DLink():
    '''双链表'''
    def __init__(self,node=None):
        self.__head=node

    def is_empty(self):
        '''链表是否为空'''
        return self.__head == None
    def add(self,item):
        node = DoubleNode(item)
        if self.is_empty():
            node.next = self.__head
            self.__head = node
        else:
            node.next = self.__head
            self.__head = node
            node.next.prev = node
    def select(self):
        cur=self.__head
        while cur != None:
            print(cur.iterm)
            cur=cur.next

if "__main__" == __name__:
    s = DLink()
    s.add(1)
    s.add(2)
    s.select()
    # s=simpleLink()
    # s.add(1)
    # s.add(2)
    # s.select()

你可能感兴趣的:(python 实现链表)