Python数据结构-链表

自己实现一遍果然感觉不一样

  1. Python实现单链表

class SingleNode(object):
    """单个节点"""
    def __init__(self, item):
        # 表元素
        self.item = item
        # 指向下一节的链接
        self.next = None

class SingleLinkList(object):
    """单链表"""
    def __init__(self):
        # 初始表头部指向None
        self._head = None

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

    def length(self):
        count = 0
        # 当前项指向表头
        cur = self._head
        # 当项不为空,向后移动
        while cur != None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        cur = self._head
        while cur != None:
            print(cur.item, end='')
            cur = cur.next
        print('')

    def add(self, item):
        # 生成单个节点类
        node = SingleNode(item)
        node.next = self._head
        self._head = node

    def append(self, item):
        node = SingleNode(item)
        # 如果链表为空,_head指向新节点
        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):

        # 插入位置小于0
        if pos <= 0:
            self.add(item)
        # 位置超出末位
        elif pos > (self.length()-1):
            self.append(item)
        # 其他
        else:
            node = SingleNode(item)
            pre = self._head  # pre 为 pos-1 位置的节点
            count = 0
            while count < (pos-1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node

    def remove(self, item):
        node = SingleNode(item)
        cur = self._head
        pre = None

        while cur != None:
            # 如果找到指定元素
            if cur.item == node.item:
                if not pre:  
                    # 第一个节点相同,即删除头节点
                    self._head = node.next
                else:
                    pre.next = cur.next
                break
            # 否则,按链表后移节点
            else:
                pre = cur
                cur = cur.next

    def search(self, item):
        """查找元素是否存在,返回True/False"""
        node = SingleNode(item)
        cur = self._head
        while cur != None:
            if cur.item == node.item:
                return True
            cur = cur.next
        return False

def main():
    link_list = SingleLinkList()
    print(link_list.is_empty())
    link_list.add(1)
    link_list.add(4)
    link_list.insert(0, 2)
    link_list.append(3)
    print('是否有1: ', link_list.search(1))
    link_list.travel()
    print('长度: ', link_list.length())
    link_list.remove(1)
    link_list.travel()

if __name__ == '__main__':
    main()
  1. Python实现单项循环链表

class SingleNode(object):
    """单节点"""
    def __init__(self, item):
        self.item = item
        self.next = None

class SinCycLinkedlist(object):
    """单项循环链表"""
    def __init__(self):
        self._head = None

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

    def length(self):
        # 头部为空
        if self.is_empty():
            count = 0
        else:
            # 循环直到 next 不指向头部
            count = 1
            cur = self._head
            while cur.next != self._head:
                count += 1
                cur = cur.next
        return count
    
    def travel(self):
        if self.is_empty():
            return
        cur = self._head
        print(cur.item, end=' ')
        while cur.next != self._head:
            cur = cur.next
            print(cur.item, end=' ')
        print('')

    def add(self, item):
        node = SingleNode(item)
        # 空链表
        if self.is_empty():
            self._head = node
            node.next = node
        else:
            node.next = self._head
            # 将链表末尾指向新节点
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            cur.next = node
            self._head = node

    def append(self, item):
        node = SingleNode(item)
        # 空链表
        if self.is_empty():
            self._head = node
            node.next = node
        else:
            # 链表末尾指向新节点,新节点指向表头
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            cur.next = node
            node.next = self._head

    def remove(self, item):
        cur = self._head
        pre = None
        # 链表为空
        if self.is_empty():
            return
        # 移除的首项
        if item == self._head.item:
            # 链表只有一项
            if self.length() == 1:
                self._head = None
            # 头部和尾部 指向移除项的next, 
            else:
                while cur.next != self._head:
                    cur = cur.next
                cur.next = self._head.next
                self._head = self._head.next
        else:
            pre = self._head
            while cur.next != self._head:
                if cur.item == item:
                    pre.next = cur.next
                    return
                pre = cur
                cur = cur.next
            # 删除的尾项
            if cur.item == item:
                pre.next = self._head
               
    def insert(self, pos, item):
        # 超出链表项
        if pos >= self.length():
            self.append(item)
        # 插在头部
        elif pos <= 0:
            self.add(item)
        # 中间位置
        else:
            node = SingleNode(item)
            cur = self._head
            count = 0
            while count < (pos-1):
                count += 1
                cur = cur.next
            node.next = cur.next
            cur.next = node

    def search(self, item):
        if self.is_empty():
            return False
        cur = self._head
        if item == cur.item:
            return True
        while cur.next != self._head:
            cur = cur.next
            if cur.item == item:
                return True
        return False


def main():
    li = SinCycLinkedlist()
    print(li.is_empty())
    li.add(1)
    li.add(23)
    li.append(4)
    li.travel()
    li.remove(4)
    li.remove(56)
    li.travel()
    li.insert(0, 11)
    li.insert(2, 5)
    li.insert(6, 8)
    li.travel()
    print(li.length())
    print(li.search(9))
    print(li.search(5))


if __name__ == '__main__':
    main()

  1. Python实现双向链表

class Node(object):

    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None


class DLinkList(object):

    def __init__(self):
        self._head = None

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

    def length(self):
        count = 0
        cur = self._head
        while cur != None:
            cur = cur.next
            count += 1
        return count

    def travel(self):
        # 空链表
        cur = self._head
        while cur != None:
            print(cur.item, end=' ')
            cur = cur.next
        print('')

    def add(self, item):
        node = Node(item)
        # 空链表
        if self.is_empty():
            self._head = node
        else:
            node.next = self._head
            self._head.prev = node
            self._head = node

    def append(self, item):
        node = Node(item)
        # 空链表
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next != None:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def insert(self, pos, item):
        # 位置小于0
        if pos <= 0:
            self.add(item)
        # 位置大于末位
        elif pos >= self.length():
            self.append(item)
        # 位置在中间
        else:
            cur = self._head
            count = 0
            while count < (pos-1):
                cur = cur.next
                count += 1
            node = Node(item)
            node.next = cur.next
            node.prev = cur
            cur.next.prev = node
            cur.next = node

    def remove(self, item):
        # 空链表
        if self.is_empty():
            return
        else:
            cur = self._head
            # 删除的是首项
            if cur.item == item:
                # 链表仅有一项
                if cur.next == None:
                    self._head = None
                # 链表不止一项
                else:
                    cur.next.prev = None
                    self._head = cur.next
                return
            # 删除的是中间项
            while cur != None:
                if cur.item == item:
                    cur.next.prev = cur.prev
                    cur.prev.next = cur.next
                    break
                cur = cur.next

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


if __name__ == '__main__':
    li = DLinkList()
    print('是否是空链表:', li.is_empty())
    li.append(9)
    li.append(10)
    li.add(8)
    li.add(5)
    li.insert(-1, 6)
    li.travel()
    li.remove(6)
    li.travel()
    print('length:', li.length())
    print('是否有99:', li.search(99))
    print('是否有8:', li.search(8))

    原文作者:大白杏仁
    原文地址: https://www.jianshu.com/p/06a0e3c433c6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞