python实现单链表

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


class LinkedList:
    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        """链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        cur = self.__head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        cur = self.__head
        while cur != None:
            print(cur.data)
            cur = cur.next
        return

    def add(self, item):
        """链表头部新增节点"""
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def push(self, item):
        """链表尾部push节点"""
        node = Node(item)
        cur = self.__head
        if not cur:
            self.__head = node
            return
        while cur.next != None:
            cur = cur.next
        cur.next = node

    def insert(self, pos, item):
        """链表中间插入节点"""
        if pos <= 0:
            self.add(item)
        elif pos > self.length() - 1:
            self.push(item)
        else:
            node = Node(item)
            cur = self.__head
            count = 0
            while count < pos - 1:
                count += 1
                cur = cur.next
            node.next = cur.next
            cur.next = node

    def remove(self, item):
        """链表删除指定元素"""
        cur = self.__head
        if cur.data == item:
            self.__head = cur.next
            return
        while cur.next.data != item:
            cur = cur.next
        cur.next = cur.next.next

    def search(self, pos):
        """链表查找指定序号元素"""
        cur = self.__head
        if not pos:
            return cur
        count = 0
        while count != pos:
            count += 1
            cur = cur.next
        return cur

 

posted @ 2020-04-04 15:28  花红正合嗅  阅读(196)  评论(0编辑  收藏  举报