python实现单链表

单链表

  • 单链表的方法
    is_empty() 链表是否为空
    length() 链表长度
    travel() 遍历整个链表
    add( item) 链表头部添加元素
    append( item) 链表尾部添加元素
    insert( pos, item) 指定位置添加元素
    remove( item) 删除节点
    search( item) 查找节点是否存在
class SingleNode(object):
    '''
    创建节点
    self.item:节点的值
    self.next:指向下一个节点域
    '''
    def __init__(self, item):
        self.item = item
        self.next = None

class SingleLinkList(object):
    """实现链表的功能"""
    def __init__(self):
        #  设置头结点
        self.__head = None

    def is_empty(self):
        """链表是否为空"""
        #  判断头结点是否为空,如果头结点为空则代表链表为空,返回True
        return self.__head == None

    def length(self):
        """链表长度"""
        #  创建两个变量count,cur,一个用于存储链表长度,一个用于遍历链表
        count = 0
        cur = self.__head
        while cur != None:
            #  如果头结点不为空,则让count加1,让cur指向下一个节点,如果cur为空则退出循环
            count += 1
            cur = cur.next
        #  返回链表长度
        return count

    def travel(self):
        """遍历整个链表"""
        #  创建一个变量用于遍历链表
        cur = self.__head
        while cur != None:
            #  输出链表值,每次输出后让cur指向下一个节点
            print(cur.item,end='  ')
            cur = cur.next
        print()

    def add(self, item):
        """链表头部添加元素"""
        #  先创建一个节点用于保存
        node = SingleNode(item)
        #  将新节点的next指向原链表的头节点
        node.next = self.__head
        #  将新节点保存为链表的头结点
        self.__head = node

    def append(self, item):
        """链表尾部添加元素"""
        #  先创建一个节点用于保存
        node = SingleNode(item)
        #  判断链表是否为空,如果为空则直接保存为头结点
        if self.is_empty():
            self.__head = node
        #  若不为空,则找到尾部,将尾结点的next指向新节点
        else:
            cur = self.__head
            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.append(item)
        #  若都不是,则指定位置插入
        else:
            #  创建一个新节点和count计算到那个位置了
            node = SingleNode(item)
            count = 0
            #  保存所要查入位置的上一个元素,因为要将它的节点域指向新节点
            per = self.__head
            #  找到指定位置
            while count < (pos-1):
                per = per.next
                count += 1
            #  将新节点的节点域指向原先位置的节点
            node.next = per.next
            #  将插入位置的前一个节点的的节点域指向新节点
            per.next = node

    def remove(self, item):
        """删除节点"""
        #  创建游标用于遍历链表
        cur = self.__head
        #  保存所要查入位置的上一个元素
        per = None
        #  查找元素
        while cur != None:
            #  如果找到了
            if cur.item == item:
                #  如果是在第一个位置找到的
                if per == None:
                    #  将头结点指向第二个节点
                    self.__head = cur.next
                #  如果不在第一个位置
                else:
                    #  将要删除节点的前一个节点域指向要删除位置的后一个节点
                    per.next = cur.next
                break
            #  如果没找到
            else:
                per = cur
                #  让游标指向下一个节点
                cur = cur.next

    def search(self, item):
        """查找节点是否存在,有则返回True,没有返回False"""
        cur = self.__head
        #  遍历链表查看元素是否存在
        while cur != None:
            if cur.item == item:
                return True
            else:
                cur = cur.next
        return False

if __name__ == '__main__':
    #  创建空链表
    l1 = SingleLinkList()

    #  判断链表是否为空,返回布尔值
    print("判断链表是否为空:", l1.is_empty())

    #  获取链表长度
    print("链表长度:", l1.length())

    #  向头部添加节点
    for i in range(5, 15):
        l1.add(i)

    #  向尾部添加元素
    l1.append('hello world!')

    #  指定位置添加元素
    l1.insert(7,'你好')

    #  删除元素
    l1.remove('hello world!')

    #  查看元素是否存在
    print('元素是否存在', l1.search(22))

    #  遍历链表
    l1.travel()

    #  判断链表是否为空,返回布尔值
    print("判断链表是否为空:", l1.is_empty())

    #  获取链表长度
    print("链表长度:", l1.length())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值