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]
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南岸青栀*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值