链表相关方法的实现

链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是每一个结点(数据存储单元)里存放下一个结点的信息(即地址)

class Link():
    def __init__(self):
        self._head = None  # 头节点

    def travel(self):  # 遍历整个链表
        cur = self._head
        while cur:
            print(cur.item)
            cur = cur.next

    def add(self, item):  # 链表头部插入节点
        node = Node(item)
        node.next = self._head
        self._head = node

    def append(self, item):  # 链表尾部追加节点
        node = Node(item)
        if self._head is None:
            self._head = node
            return
        cur = self._head
        while cur.next:
            cur = cur.next
        cur.next = node

    def insert(self, pos, item):  # 指定位置插入节点
        node = Node(item)
        if pos > self.length():
            return
        if pos == 0:
            node.next = self._head
            self._head = node
            return

        pre = None
        cur = self._head
        for i in range(pos):
            pre = cur
            cur = cur.next
        pre.next = node
        node.next = cur

    def remove(self, item):  # 删除节点
        pre = None
        cur = self._head
        if item == cur.item:
            self._head = cur.next
            return
        while cur:
            if cur.item == item:
                pre.next = cur.next
                break
            pre = cur
            cur = cur.next

    def reverse(self):  # 链表的反转
        pre = None
        cur = self._head
        cur_next = cur.next
        while cur:
            cur.next = pre
            pre = cur
            cur = cur_next
            if cur != None:
            	cur_next = cur_next.next
        
        self._head = pre
        
       
    def is_empty(self):  # 链表是否为空
        return self._head is None

    def length(self):  # 链表的长度
        count = 0
        cur = self._head
        while cur:
            count += 1
            cur = cur.next
        return count

    def search(self, item):  # 查找节点是否存在
        cur = self._head
        find = False
        while cur:
            if cur.item == item:
                find = True
            cur = cur.next
        return find

链表反转示意图
链表相关方法的实现_第1张图片

你可能感兴趣的:(链表相关方法的实现)