python单向链表和双向链表的图示代码说明

116 篇文章 5 订阅

图示说明:

单向链表:

insert、 remove、 update、pop方法

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

    def __str__(self):
        return str(self.data)


# 通过单链表构建一个list的结构: 添加  删除  插入   查找 获取长度  判断是否为空...
# list1 = []  list1.append(5)     [5,]             slist =  SingleList()   slist.append(5)
class SingleList:
    def __init__(self, node=None):
        self._head = node

    def isEmpty(self):
        return self._head == None

    def append(self, item):
        # 尾部添加
        node = Node(item)
        if self.isEmpty():
            self._head = node
        else:
            cur = self._head
            while cur.next != None:
                cur = cur.next
            cur.next = node

    # 求长度
    def len(self):
        cur = self._head
        count = 0

        while cur != None:
            count += 1
            cur = cur.next

        return count

    # 遍历
    def print_all(self):
        cur = self._head
        while cur != None:
            print(cur)
            cur = cur.next

    def pop(self, index):
        if index < 0 or index >= self.len():
            raise IndexError('index Error')
        if index == 0:
            self._head = self._head.next
        else:
            cur = self._head
            # 找到当前下标的前一个元素
            while index - 1:
                cur = cur.next
                index -= 1
            # 修改的next的指向位置
            cur.next = cur.next.next

    def insert(self, index, item):
        if index < 0 or index >= self.len():
            raise IndexError('index Error')
        if isinstance(item, Node):
            raise TypeError('不能是Node类型')
        else:
            node = Node(item)

        if index == 0:
            node.next = self._head
            self._head = node
        else:
            cur = self._head

            while index - 1:
                cur = cur.next
                index -= 1

            node.next = cur.next
            cur.next = node

    def update(self, index, new_item):
        if index < 0 or index >= self.len():
            raise IndexError('index Error')
        if isinstance(new_item, Node):
            raise TypeError('不能是Node类型')
        else:
            node = Node(new_item)

        if index == 0:
            node.next = self._head.next
            self._head = node
        else:
            cur = self._head
            node.next = cur.next.next
            cur.next = node



    def remove(self, item):
        if isinstance(item, Node):
            raise TypeError('不能是Node类型')
        else:
            node = Node(item)

        cur = self._head
        while cur == node:
            cur = cur.next
        cur.next = cur.next.next


if __name__ == '__main__':
    slist = SingleList()
    print(slist.isEmpty())  # True
    print(slist.len())

    slist.append(5)
    print(slist.isEmpty())  # False
    print(slist.len())  # 1

    slist.append(8)
    slist.append(6)
    slist.append(3)
    slist.append(1)
    print(slist.isEmpty())  # True
    print(slist.len())
    print('---------------------')
    slist.print_all()

    print('----------pop-------------')
    slist.pop(2)
    slist.print_all()

    print('--------insert-------')
    slist.insert(1, 19)
    slist.print_all()

    print('--------update-------')
    slist.update(1, 18)
    slist.print_all()

    print('--------remove-------')
    slist.remove(18)
    slist.print_all()

双向链表:

insert、 remove、 update方法

'''
双向链表
'''


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

    def __str__(self):
        return str(self.data)


class DoubleList:
    def __init__(self):
        self._head = None

    def isEmpty(self):
        return self._head == None

    def append(self, item):
        # 尾部添加
        node = Node(item)
        if self.isEmpty():
            self._head = node
        else:
            cur = self._head
            while cur.next != None:
                cur = cur.next
            cur.next = node

        # 求长度

    def add(self, item):
        node = Node(item)
        if self.isEmpty():
            self._head = node
        else:
            node.next = self._head
            self._head.prev = node
            self._head = node

    def len(self):
        cur = self._head
        count = 0

        while cur != None:
            count += 1
            cur = cur.next

        return count

    def print_all(self):
        cur = self._head
        while cur != None:
            print(cur)
            cur = cur.next

    def insert(self, index, item):
        if index < 0 or index >= self.len():
            raise IndexError('index Error')
        if isinstance(item, Node):
            raise TypeError('不能是Node类型')


        if index == 0:
            node = Node(item)
            node.next = self._head
            self._head.prev= node
            self._head = node

        else:
            cur = self._head
            node = Node(item)

            while index - 1:
                cur = cur.next
                index -= 1
            #cur 是xindex的前一个节点
            # 设置node节点的前一个是cur节点
            node.prev = cur
            #设置node的后一个节点
            node.next = cur.next
            #设置cur下一个节点的prev指向node
            cur.next.prev = node
            # 设置cur的下一个节点
            cur.next = node


    def remove(self, item):
        if self.isEmpty():
            raise ValueError('double link list is empty')
        else:
            cur = self._head
            if cur.data == item:
                #删除的是头节点
                if cur.next ==None:
                    #只有头节点
                    self._head = None
                else:
                    # 除了头部节点,还有其他节点
                    cur.next.prve = None
                    self._head = cur.next
            else:
                while cur != None:
                    if cur.data == item:
                        cur.prev.next = cur.next
                        cur.next.prve = cur.prev # 双向的
                        break
                    cur = cur.next

    def update(self, index, new_item):
        if index < 0 or index >= self.len():
            raise IndexError('index Error')
        if isinstance(new_item, Node):
            raise TypeError('不能是Node类型')
        else:
            node = Node(new_item)
            cur = self._head
            #获取cur
            while index :
                cur = cur.next
                index -= 1
            node.prev = cur.prev
            cur.prev.next = node
            node.next =cur.next
            cur.next.prev = node




        # if index == 0:
        #     node.next = self._head.next
        #     node.prev = self._head.prev
        #     self._head = node
        # else:
        #     cur = self._head
        #     node.next = cur.next.next
        #     node.prev = cur.prev
        #     cur.next = node
        #     cur.prev = node


if __name__ == '__main__':
    dlist = DoubleList()

    print(dlist.len())
    print(dlist.isEmpty())

    # dlist.append(6)
    # dlist.append(9)
    # dlist.append(5)
    # print(dlist.len())
    # print(dlist.isEmpty())
    # dlist.print_all()

    dlist.add(6)
    dlist.add(9)
    dlist.add(5)

    dlist.print_all()

    print('--------insert-------')
    dlist.insert(1, 19)
    dlist.print_all()
    print('--------update-------')
    dlist.update(1, 1)
    dlist.print_all()
    print('--------remove-------')
    dlist.remove(9)
    dlist.print_all()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网络毒刘

授人玫瑰,手有余香。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值