链表的创建

class Node():
    def __init__(self,data):
        self.data=data
        self.next=None
class linklist:
    def __init__(self,li,method='tail')
       self.head=None
       if method=='tail':
            self.creat_tail_link(self,li)
        elif method=='head'
            self.creat_head_link(self,li)
        else:
            raise ValueError('传入方式错误')
    def creat_head_link(self,li):
        self.head=Node(0)
        for v in li:
            n=Node(v)
            n.next=self.head.next
            self.head.next=n
            self.head.data+=1 
    def tail_linklist(self,li):
        self.head=Node(0)
        tail=self.head
        for v in li:
            n=Node(V)
            n.next=self.head.next
            self.head.next=n
            self.head.data+=1
    def traverse_linklist(self):
        p=self.head.next
        while p:
            print(p.data)
            p=p.next
    def __len__(self):
        return self.head.data
li=linklist([1,2,3,4])
li.traverse_linklist()
            

 

你可能感兴趣的:(链表的创建)