赞
踩
您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。
在链表类中实现这些功能:
注意处理索引index = 0和长度length = 1的情况
#!/usr/bin/env python # _*_ coding:utf-8 _*_ class Nodelist(object): def __init__(self, item=None): self.val=item self.next=None class MyLinkedList: def __init__(self): """ Initialize your data structure here. """ self.__head=None self.length=0 def isEmpty(self): return self.__head == None 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 if index < 0 or self.length <= index: return -1 while cur: if count == index: return cur.val count+=1 cur=cur.next 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=Nodelist(val) node.next=self.__head self.__head=node self.length+=1 def addAtTail(self, val: int) -> None: """ Append a node of value val to the last element of the linked list. """ node=Nodelist(val) cur=self.__head while cur.next: cur=cur.next cur.next=node self.length+=1 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=Nodelist(val) cur=self.__head pre=None count=0 if index < 0 or index > self.length: return -1 elif index == 0: self.__head=node node.next=cur else: while cur: pre=cur cur=cur.next count+=1 if count == index: pre.next=node node.next=cur self.length+=1 def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ cur=self.__head pre=None count=0 if index < 0 or index >= self.length: return -1 elif index == 0: self.__head=cur.next else: if self.length == 1: self.__head=None else: while cur: pre=cur cur=cur.next count+=1 if count == index: pre.next=cur.next self.length-=1 def travel(self): cur=self.__head while cur.next: print(cur.val, end="") cur=cur.next linkedList=MyLinkedList() linkedList.addAtHead(2) print(linkedList.get(1)) linkedList.addAtHead(2) linkedList.addAtHead(7) linkedList.addAtHead(3) linkedList.addAtHead(2) linkedList.addAtHead(5)
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/design-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。