单向不循环链表(创建、遍历、增、删、查找、判空)

# coding: utf-8


# 链表节点
class Node(object):
    def __init__(self, item):
        self.item = item
        self.next = None


# 单向不循环链表
class LinkList(object):
    def __init__(self):
        self._head = None

    def is_empty(self):
        # 判断链表是否为空
        return self._head is None

    def length(self):
        # 链表长度
        num = 0
        cur = self._head
        while cur is not None:
            num += 1
            cur = cur.next
        return num

    def travel(self):
        # 遍历链表
        cur = self._head
        while cur is not None:
            print(cur.item, end=' ')
            cur = cur.next
        print('length:', self.length())

    def add(self, item):
        # 头插
        node = Node(item)
        node.next = self._head
        self._head = node

    def append(self, item):
        # 尾插
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next is not None:
                cur = cur.next
            cur.next = node

    def insert(self, pos, item):
        # 在pos位置插
        if pos <= 0:
            self.add(item)
        elif pos >= self.length():
            self.append(item)
        else:
            node = Node(item)
            cur = self._head
            pos_cur = 0
            while pos_cur + 1 != pos:
                cur = cur.next
                pos_cur += 1
            node.next = cur.next
            cur.next = node

    def remove(self, item):
        # 链表中找到元素item并从链表中移除
        if self.is_empty():
            return 'List is empty.'
        cur = self._head
        if cur.item == item:
            self._head = cur.next
        else:
            while cur.next is not None and cur.next.item != item:
                cur = cur.next
            if cur.next.item == item:
                cur.next = cur.next.next

    def search(self, item):
        # 查找元素item是否在链表中
        cur = self._head
        while cur is not None:
            if cur.item == item:
                return True
            else:
                cur = cur.next
        return False


if __name__ == '__main__':
    a = LinkList()
    a.travel()
    a.append(1)
    a.travel()
    a.append(2)
    a.travel()
    a.add(3)
    a.travel()
    a.append(100)
    a.travel()
    a.insert(1, 600)
    a.travel()
    a.insert(0, 700)
    a.travel()
    a.insert(6, 1314)
    a.travel()
    a.insert(6, 520)
    a.travel()
    a.remove(1)
    a.travel()
    a.remove(1314)
    a.travel()
    a.remove(700)
    a.travel()
    print(a.search(100))
    print(a.search(1314))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值