python数据结构与算法:单向链表

单链表:python实现及其对应的 增删查检 操作

 

#####################  P4.1-P4.8 单向链表  ###########################
#coding:utf-8
class Node(object):
    def __init__(self,elem):
          self.elem = elem
          self.next = None

class SinglelinkList(object):
    """SinglelinkList"""
    def __init__(self,node = None):#默认参数
        self.__head = node

    def is_empty(self):
        return self.__head == None

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

    def length(self):
        """length of list 遍历 借助 Cursor 指针或者游标计数"""
        cur = self.__head#cur游标 遍历节点 不断移动
        count = 0
        while cur != None:# cur.next = None
              count+=1
              cur = cur.next
        return count
    def __add__(self, item):
        """nedd to add node"""
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def append(self,item):
        node = Node(item)        #node 实例化
        if self.is_empty():
           self._head = node
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node
    def insert(self,pos,item):
        """:param pos  从0 开始 """
        pre = self.__head
        count = 0
        if pos<0:
            self.__add__(item)
        elif pos>(self.length()-1):
            self.append(item)
        else:
            while (count<(pos-1)):
                count+=1
                pre = pre.next
            node =Node(item)
            node.next = pre.next
            pre.next = node
    def remove(self,item):
        cur = self.__head
        pre = None
        while cur!= None:
            if cur.elem == item:
                if pre ==None:
                   self.__head=cur.next
                else:
                   pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next

    def search(self,item):
        cur = self.__head
        while cur!= None:
            if cur.elem == item:
                return  True
            else:
                cur = cur.next
        return False

# single_obe = SinglelinkList()
if __name__ =="__main__":
    ll = SinglelinkList()
    print(ll.is_empty())
    print(ll.length())

    ll.append(1)
    print(ll.is_empty())
    print(ll.length())

    ll.append(2)
    ll.__add__(8)
    ll.append(1)
    ll.append(3)
    ll.append(1)
    ll.append(3)
    ll.insert(-1,9)
    ll.insert(4, 119)
    ll.insert(8, 1234)
    ll.travel()
### 9 8 1 3 119 1 3 1234
    ll.remove(1234)
    ll.travel()

 

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值