LeetCode:707. 设计链表(python3)

Posted 南岸青栀*

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:707. 设计链表(python3)相关的知识,希望对你有一定的参考价值。

707. 设计链表

在这里插入图片描述
既然遇到这个题,就再次回顾一下,链表的创建吧

法1:规规矩矩写链表

#初始化节点函数
class Node:
    def __init__(self,val):
        self.val = val
        self.next = None
class MyLinkedList:
	#初始化链表
    def __init__(self,node=None):
        """
        Initialize your data structure here.
        """
        #如果还没有链表,则调用的时候,出现一个空链表
        if node!=None:
            headNode = Node(node)
            self.__head=headNode
        #如果链表输入链表第一个值,则将第一个节点设为链表头结点
        else:
            self.__head=node


	#根据要求:该函数为获取链表中第 index 个节点的值。如果索引无效,则返回-1。
    def get(self, index: int) -> int:
        """
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        """
        count = 0
        cur = self.__head
        while cur:
            if count == index:
                return cur.val
            count += 1          
            cur = cur.next
        return -1
        

	#首先编写的就是头插法或者尾插法
    def addAtHead(self, val: int) -> None:
        """
        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
        """
        #将头结点设置为当前节点
        node = Node(val)
        node.next = self.__head
        self.__head = node
        
            

	#尾插法
    def addAtTail(self, val: int) -> None:
        """
        Append a node of value val to the last element of the linked list.
        """
        node = Node(val)
        #判断,如果头结点为None 则将当前节点设置为头结点
        if self.__head == None: self.__head = node
        else:
        	#如果头结点不为None:遍历链表,直到最后一个节点
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            #尾部插入
            cur.next = node

	#指定位置插入
    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        node = Node(val)
        # while
        #特殊情况index<=0 则说明为头插法
        if index <= 0: self.addAtHead(val)
        #index>链表长度,则为尾插法
        #这里为了方便使用,自己定义了一个计算链表长度的函数
        elif index > self.length(): self.addAtTail(val)
        else:
        #正常情况
            count = 0
            pre = self.__head
            while count < (index-1):
                pre = pre.next
                count += 1
            node.next = pre.next
            pre.next = node




	#删除指定节点
    def deleteAtIndex(self, index: int) -> None:
        """
        Delete the index-th node in the linked list, if the index is valid.
        """
        #判断特殊情况
        if index < 0: return
        #如果为删除结点为头节点
        elif index == 0:
            self.__head = self.__head.next
        else:
        #正常情况
            count = 0
            cur = self.__head
            while count < (index-1):
                cur = cur.next
                count += 1
            cur.next = cur.next.next if cur.next != None else None
        
	#为了测试头插法和尾插法写的是否正确,自己写的一个遍历输出函数
    def bianli(self):
        cur = self.__head
        while cur:
            print(cur.val)
            cur = cur.next
    #为了简化操作自己定义了计算链表长度的函数
    def length(self):
        count = 0
        cur = self.__head
        while cur:
            cur = cur.next
            count += 1
        return count


# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)


# obj.addAtHead(2)
# obj.addAtHead(1)



# obj.addAtIndex(1,2)
# obj.get(1)
# obj.deleteAtIndex(1)
# obj.bianli()
# print(obj.get(1))

看完运行时间超100%的范程之后,觉得我的智商被碾压了。

法2:巧用列表法(开辟新思路)

直接使用列表

class MyLinkedList:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.linkedlist = []

    def get(self, index: int) -> int:
        """
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        """
        if index < 0 or index >= len(self.linkedlist):
            a = -1
        else:
            a = self.linkedlist[index]
        return a

    def addAtHead(self, val: int) -> None:
        """
        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
        """
        self.linkedlist.insert(0, val)

    def addAtTail(self, val: int) -> None:
        """
        Append a node of value val to the last element of the linked list.
        """
        self.linkedlist.append(val)

    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        if index < 0:
            self.linkedlist.insert(0, val)
        elif 0 <=index <= len(self.linkedlist):
            self.linkedlist.insert(index, val)

    def deleteAtIndex(self, index: int) -> None:
        """
        Delete the index-th node in the linked list, if the index is valid.
        """
        if 0 <= index < len(self.linkedlist):
            del self.linkedlist[index]

以上是关于LeetCode:707. 设计链表(python3)的主要内容,如果未能解决你的问题,请参考以下文章

707链表-设计链表

707链表-设计链表

图解 LeetCode 707一题学会链表的 5 种操作。

图解 LeetCode707:一题学会链表的 5 种操作。

Java算法 每日一题 编号707:设计链表

Java算法 每日一题 编号707:设计链表