1. 程式人生 > 其它 >leetcode-707:設計連結串列

leetcode-707:設計連結串列

LC 設計連結串列

題目

題目連結

設計連結串列的實現。您可以選擇使用單鏈表或雙鏈表。單鏈表中的節點應該具有兩個屬性:val 和 next。val 是當前節點的值,next 是指向下一個節點的指標/引用。如果要使用雙向連結串列,則還需要一個屬性 prev 以指示連結串列中的上一個節點。假設連結串列中的所有節點都是 0-index 的。

在連結串列類中實現這些功能:

  • get(index):獲取連結串列中第 index 個節點的值。如果索引無效,則返回-1。
  • addAtHead(val):在連結串列的第一個元素之前新增一個值為 val 的節點。插入後,新節點將成為連結串列的第一個節點。
  • addAtTail(val):將值為 val 的節點追加到連結串列的最後一個元素。
  • addAtIndex(index,val):在連結串列中的第 index 個節點之前新增值為 val 的節點。如果 index 等於連結串列的長度,則該節點將附加到連結串列的末尾。如果 index 大於連結串列長度,則不會插入節點。如果index小於0,則在頭部插入節點。
  • deleteAtIndex(index):如果索引 index 有效,則刪除連結串列中的第 index 個節點。

示例:

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(
1); linkedList.addAtTail(3); linkedList.addAtIndex(1,2); //連結串列變為1-> 2-> 3 linkedList.get(1); //返回2 linkedList.deleteAtIndex(1); //現在連結串列是1-> 3 linkedList.get(1); //返回3

在這裡插入圖片描述

解題:

方法一:單鏈表

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class
MyLinkedList: def __init__(self): self.size = 0 self.head = ListNode(0) # sentinel node as pseudo-head 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 is invalid if index < 0 or index >= self.size: return -1 curr = self.head # index steps needed # to move from sentinel node to wanted index for _ in range(index + 1): curr = curr.next return curr.val 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.addAtIndex(0, val) def addAtTail(self, val: int) -> None: """ Append a node of value val to the last element of the linked list. """ self.addAtIndex(self.size, 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 is greater than the length, # the node will not be inserted. if index > self.size: return # [so weird] If index is negative, # the node will be inserted at the head of the list. if index < 0: index = 0 self.size += 1 # find predecessor of the node to be added pred = self.head for _ in range(index): pred = pred.next # node to be added to_add = ListNode(val) # insertion itself to_add.next = pred.next pred.next = to_add def deleteAtIndex(self, index: int) -> None: """ Delete the index-th node in the linked list, if the index is valid. """ # if the index is invalid, do nothing if index < 0 or index >= self.size: return self.size -= 1 # find predecessor of the node to be deleted pred = self.head for _ in range(index): pred = pred.next # delete pred.next pred.next = pred.next.next

方法二:雙鏈表(未完成)