链表python

链表的增加,删除,插入,查找及打印。

#encoding=utf-8

class Node:
    def __init__(self,value=None,next=None):
        self.value = value
        self.next = next

class LinkedList(object):

    def __init__(self,head=None):
        self.head = head

    def __len__(self):
        count =0 
        if self.head is None:
            return count
        node = self.head
        while node:
            count+=1
            node = node.next 
        return count

    def append(self,node):
        if self.head is None:
            self.head = node
        else:
            cur_node = self.head
            while cur_node.next is not None:
                cur_node = cur_node.next
            cur_node.next = node

    def find(self,value):
        if self.head is None:
            return None
        else:
            cur_node = self.head
            while cur_node:
                if cur_node.value == value:
                    return cur_node
                cur_node = cur_node.next
            return None

    def delete(self,value):
        if self.head is None:
            return None
        elif self.head.value == value:
            tmp = self.head 
            self.head=self.head.next
            return tmp
        else:
            cur_node = self.head 
            before_node = None           
            while cur_node:   
                if cur_node.value == value:
                    before_node.next=cur_node.next
                    return cur_node
                before_node = cur_node 
                cur_node = cur_node.next
            return None
    
    def insert_front(self,data):
        if self.head is None:
            self.head = Node(data)
        else:
            tmp = self.head
            self.head = Node(data)
            self.head.next = tmp
        return self.head

        
   
    def get_all(self):
        data = []
        if self.head is None:
            return data
        else:
            cur_node = self.head
            while cur_node:
                data.append(cur_node.value)
                cur_node = cur_node.next
            return data

a=LinkedList()
a.append(Node(1))
a.append(Node(2))
a.append(Node(3))
print(a.insert_front(4))
print(a.get_all())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值