单向链表

class Node(object):
    """节点类"""
    def __init__(self, item):
        #记录节点的内容
        self.item = item
        #记录下一个节点
        self.next=None

class SingLinkList(object):
    def __init__(self):
        #记录头节点
        self.__head=None
    def is_empty(self):
        """链表是否为空"""
        # 判断
        return self.__head is None
    def length(self):
        """链表长度"""
        # 定义游标变量,从头往后遍历
        cur=self.__head
        count=0
        while cur is not None:
            count+=1
            #游标往后移动
            cur= cur.next
        return count
    def travel(self):
        """遍历整个链表"""
        #定义游标变量。从头往后遍历
        cur=self.__head
        while cur is not  None:
            #输出当前节点内容
            print(cur.item,end=" ")
            #游标往后移动
            cur=cur.next
        print()
    def add(self,item):
        """链表头部添加元素"""
        #创建节点对象
        node=Node(item)
        # 新节点指向原来的头节点
        node.next=self.__head
        # 让头节点记录新节点
        self.__head=node
    def append(self,item):
        """链表尾部添加元素"""
        #判断链表是否为空
        if self.is_empty():
            self.add(item)
            return
        #1.遍历找到尾节点
        #定义游标变量,从头到尾遍历
        cur=self.__head
        while cur.next is not None:
            # 游标往后移动
            cur=cur.next
            # 当while循环结束,cur指向的是尾节点
        # 2. 让尾节点指向新节点
        node=Node(item)
        cur.next=node

    def insert(self,pos,item):
        """指定位置添加元素"""
        # 健壮性
        if pos <= 0:
            self.add(item)
        elif pos > (self.length()-1):
            self.append(item)
        else:
            # 1. 找到pos前一个位置的节点
            cur=self.__head
            # 定义下标变量
            index = 0
            while index < (pos-1):
                # 游标往后移动
                index+=1
                cur = cur.next
            # while循环结束,cur指向的就是pos前一个位置的节点
            # 2. 插入新节点
            node = Node(item)
            #让新节点指向pos位置的节点
            node.next=cur.next
            # pos前一个位置的节点指向新节点
            cur.next=node

    def remove(self,item):
        """删除节点"""
        # 找到要删除的节点的前置节点
        cur=self.__head
        #记录当前游标的前置节点
        pre=None
        while cur is not None:
            if cur.item==item:
                # 2 删除当前节点
                #如果pre为空,证明要删除的是头节点
                if pre is None:
                    self.__head=cur.next
                else:
                    pre.next=cur.next
                    break
                pre=cur
                cur=cur.next
    def search(self,item):
        """查找当前节点是否存在"""
        cur=self.__head
        while cur is not None:
            if cur.item==item:
                return True
            cur=cur.next
            return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值