单链表,双向链表,单向循环链表python定义以及基础操作的实现

python和其他很多语言的不同之处在于python中的变量名是有实际意义的如:

a = 10

a保存的是存储10这个数值的空间的地址也称为引用

而对于C

a这个变量名就是一个代号,他不占内存。具体的c中变量名的意义可以参考:https://blog.csdn.net/CSDN_LSD/article/details/78572491

由于pythond的这个特性,python实现链表以及链表的基本操作要简单一些。

代码如下:

单链表

class Node(object):
    """定义一个节点"""
    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingleLinkList(object):
    """单链表"""
    def __init__(self, node=None):
        # 因为不需要让用户知道我的头结点在哪里所以head定义为私有的属性。
        self.__head = node

    def is_empty(self):
        """链表是否为空"""
        return self.__head is None

    def length(self):
        """链表的长度"""
        # cur游标,用来移动遍历节点
        cur = self.__head
        # count记录数量
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

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

    def add(self, item):
        """链表头部添加元素"""
        node = Node(item)
        node.next = self.__head
        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

    # pos/position:位置,方位 param:参数
    def insert(self, pos, item):
        """指定位置添加元素
        :param pos 从0开始(即将链表的第一个节点记为0节点)"""
        # pre/previous以前的,在什么之前
        if pos <= 0:
            self.add(item)
        elif pos > (self.length()-1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            while count < (pos-1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node

    def remove(self, item):
        """删除节点"""
        pre = self.__head

        # 判断是不是空链表
        if pre == None:
            return False
        # 判断是不是头结点,包含了只有一个节点情况
        elif pre.elem == item:
            self.__head = pre.next
            # pre = None
            return True
        else:
            while pre.next != None:
                if pre.next.elem == item:
                    pre.next = pre.next.next
                    return True
                else:
                    pre = pre.next
            return False
        # 也可以使用这种方法
        # cur = self.__head
        # pre = None
        # while cur != None:
        #     if cur.elem == item:
        #         # 先判断此结点是否是头节点
        #         # 头节点
        #         if cur == self.__head:
        #             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


if __name__ == '__main__':
    sll = SingleLinkList()

    print(sll.remove(4))
    sll.travel()
    print("----------")
    sll.append(2)
    print(sll.search(2))
    print(sll.remove(2))
    print("----------")
    sll.append(2)
    sll.append(3)
    sll.append(5)
    sll.append(6)
    sll.append(7)
    sll.travel()
    sll.add(1)
    sll.travel()
    sll.insert(3, 4)
    sll.travel()
    sll.remove(1)
    sll.travel()
    sll.remove(7)
    sll.travel()
    sll.remove(4)
    sll.travel()
    print(sll.remove(100))
    sll.travel()
    print(sll.search(6))

 双向链表

class Node(object):
    """节点"""

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


class DoubleLinkList(object):
    """双向链表"""

    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        """链表是否为空"""
        return self.__head is None

    def length(self):
        """链表长度"""
        # cur游标,用来移动遍历节点
        cur = self.__head
        # counter:记录数量
        counter = 0
        while cur != None:
            counter += 1
            cur = cur.next
        return counter

    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 add(self, item):
        """链表头部添加节点,头插法"""
        node = Node(item)
        node.next = self.__head
        self.__head = node
        node.next.prev = node

    def insert(self, pos, item):
        """任意位置添加节点"""
        # pos的初始值为0
        if pos <= 0:
            self.add()
        elif pos > (self.length()-1):
            self.append()
        else:
            cur = self.__head
            counter = 0
            while counter != pos:
                counter += 1
                cur = cur.next
            node = Node(item)
            node.prev = cur.prev
            cur.prev.next = node
            node.next = cur
            cur.prev = node

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

    def remove(self, item):
        """根据元素删除节点"""
        cur = self.__head
        while cur != None:
            if cur.elem == item:
                # 先判断此结点是否是头节点
                # 头节点
                if cur == self.__head:
                    self.__head = cur.next
                    if cur.next != None:
                    # 链表不只有一个节点
                        cur.next.prev = None
                else:
                    cur.prev.next = cur.next
                    if cur.next != None:
                        cur.next.prev = cur.prev
                return True
            else:
                cur = cur.next
        return False

    def search(self, item):
        """根据元素查找节点是否存在"""
        cur = self.__head
        while cur != None:
            if cur.elem == item:
                return True
            else:
                cur = cur.next
        return False


if __name__ == '__main__':
    dll = DoubleLinkList()

    print(dll.remove(4))
    dll.travel()
    print("----------")
    dll.append(2)
    print(dll.search(2))
    print(dll.remove(2))
    print("----------")
    dll.append(2)
    dll.append(3)
    dll.append(5)
    dll.append(6)
    dll.append(7)
    dll.travel()
    dll.add(1)
    dll.travel()
    dll.insert(3, 4)
    dll.travel()
    dll.remove(1)
    dll.travel()
    dll.remove(7)
    dll.travel()
    dll.remove(4)
    dll.travel()
    print(dll.remove(100))
    dll.travel()

单向循环链表

class Node(object):
    """定义一个节点"""
    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingleLinkList(object):
    """单向循环链表"""
    def __init__(self, node=None):
        # 因为不需要让用户知道我的头结点在哪里所以head定义为私有的属性。
        self.__head = node
        if node != None:
            node.next = node

    def is_empty(self):
        """链表是否为空"""
        return self.__head is None

    def length(self):
        """链表的长度"""
        if self.is_empty():
            return 0
        # cur游标,用来移动遍历节点
        cur = self.__head
        # count记录数量,因为循环不会进入最后一个节点所以初始值为1
        count = 1
        while cur.next != self.__head:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历整个链表"""
        cur = self.__head
        if cur == None:
            return
        else:
            while cur.next != self.__head:
                print(cur.elem, end=" ")
                cur = cur.next
            # 退出循环后cur指向尾节点,但是尾节点没有打印。
            print(cur.elem)

    def add(self, item):
        """链表头部添加元素"""
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = self.__head
            # 或者
            # self.__head = node
            # node.next = node
        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next
            # 循环结束后cur指向尾节点
            node.next = self.__head
            self.__head = node
            cur.next = node

    def append(self, item):
        """链表尾部添加元素"""
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = node
        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next
            # 循环结束cur指向最后一个节点
            cur.next = node
            node.next = self.__head

    # pos/position:位置,方位 param:参数
    def insert(self, pos, item):
        """指定位置添加元素
        :param pos 从0开始(即将链表的第一个节点记为0节点)"""
        # pre/previous以前的,在什么之前
        if pos <= 0:
            self.add(item)
        elif pos > (self.length()-1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            while count < (pos-1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node

    def remove(self, item):
        """删除节点"""
        pre = self.__head
        cur = self.__head
        # 判断是不是空链表
        if cur == None:
            return False
        # 判断是不是头结点
        elif cur.elem == item:
            # 判断是不是只有一个节点
            if cur.next == self.__head:
                self.__head = None
                return True
            else:
                while pre.next != self.__head:
                    pre = pre.next
                self.__head = cur.next
                pre.next = self.__head
                return True
        else:
            while pre.next != self.__head:
                if pre.next.elem == item:
                    pre.next = pre.next.next
                    return True
                else:
                    pre = pre.next
            return False

    def search(self, item):
        """查找节点是否存在"""

        cur = self.__head
        # 判断是否为空链表
        if self.__head == None:
            return False
        # 判断是不是头结点
        elif cur.elem == item:
            return True
        else:
            while cur.next != self.__head:
                if cur.elem == item:
                    return True
                else:
                    cur = cur.next
            # 循环退出后cur指向最后一个节点,但是没有进入最后一个节点
            if cur.elem == item:
                return True
        return False


if __name__ == '__main__':
    sll = SingleLinkList()
    print(sll.remove(4))
    sll.travel()
    print("----------")
    sll.append(2)
    print(sll.search(2))
    print(sll.remove(2))
    print("----------")
    sll.append(2)
    sll.append(3)
    sll.append(5)
    sll.append(6)
    sll.append(7)
    sll.travel()
    sll.add(1)
    sll.travel()
    sll.insert(3, 4)
    sll.travel()
    sll.remove(1)
    sll.travel()
    sll.remove(7)
    sll.travel()
    sll.remove(4)
    sll.travel()
    print(sll.remove(100))
    sll.travel()
    print(sll.search(6))

 

你可能感兴趣的:(经典面试题,python)