单链表的遍历以及增、删、改、查等操作的Python实现

代码正文见下方的Python代码块。
如果测试时出现异常:AttributeError: ‘NoneType’ object has no attribute ‘elem’,请检查链表头部的处理情况,是否有遗漏的情况等。另外,需要确认游标定义是否足够清晰、准确。

"""Data structure"""
# coding:utf-8
class Node(object):
	"""Define the node class"""
    def __init__(self, elem):
        self.elem = elem
        self.next = None
        
class SinglyLinkedList(object):
	"""Define the singly linked list"""
    def __init__(self, node=None):
        self.__head = node
    def is_empty(self):
		"""is_empty"""
        return self.__head == None

    def length(self):
		"""length"""
        cursor = self.__head
        count = 0
        while cursor != None:
            count += 1
            cursor = cursor.next
        return count

    def travel(self):
    	"""Ergodic the whole list"""
        cursor = self.__head
        while cursor != None:
            print(cursor.elem, end=" ")
            cursor = cursor.next
        print("")

    def add(self, item):
        """Adds an element at the head"""
        node = Node(item)
        node.next = self.__head
        self.__head = node

    def append(self, item):
        """Adds an element at the end"""
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cursor = self.__head
            while cursor.next != None:
                cursor = cursor.next
            cursor.next = node

    def insert(self, pos, item):
        """Adds an element at the specified position"""
        cursor = self.__head #The tutor defined a 'pre' instead of 'cursor'
        node = Node(item)
        count = 0
        if pos <= 0:
            self.add(item)
        elif pos > self.length()-1:
            self.append(item)
        else:
            while count < (pos-1):
                count += 1
                cursor = cursor.next
            node.next = cursor.next
            cursor.next = node

    def remove(self, item):
        """Remove a node"""
        cursor = self.__head
        if self.search(item) and self.__head.elem == item:
            self.__head = cursor.next
            print("-----%d is removed!-----"%item)
        elif self.search(item) and self.__head.elem != item:
            while cursor.next != None:
                if cursor.next.elem == item:
                    print("cursor.next.elem:%d"%item)
                    cursor.next = cursor.next.next
                    print("cursor: %s"%cursor.elem)
                else:
                    cursor = cursor.next
            print("======%d is removed!======="%item)
        else:
            print("%d doesn't exist."%item)

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

"""Test the functions:"""
if __name__ == "__main__":
    sll = SinglyLinkedList()
    print(sll.is_empty())
    print(sll.length())
    sll.append(1)
    print(sll.is_empty())
    print(sll.length())
    sll.append(2)
    sll.append(3)
    sll.append(4)
    sll.append(5)
    sll.add(9)
    sll.append(6)
    sll.append(7)
    sll.append(8)
	sll.insert(-5, 10)
    sll.insert(6, 11)
    sll.insert(7, 11)
    sll.insert(8, 11)
    sll.insert(100, 12)
    print(sll.length())
    print(sll.search(12))
    sll.travel()
    sll.remove(9)
    sll.travel()
    sll.remove(12)
    sll.travel()
    sll.remove(11)
    sll.travel()
    sll.remove(8)
    sll.travel()
    sll.remove(3)
    sll.travel()
    sll.remove(10)
    sll.travel()
    sll.remove(20)
    sll.travel()
    sll.remove(9)
    sll.travel()

你可能感兴趣的:(python,Data,Structure,数据结构,python)