@TOC
第一题 707. 设计链表 - 力扣(LeetCode)
代码 python版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 class MyLinkedList : def __init__ (self ): self.dummy = ListNode(-1 ) self.size = 0 def get (self, index: int ) -> int : if index < 0 or index >= self.size: return -1 cur = self.dummy.next i = 0 while i < index: cur = cur.next i += 1 return cur.val def addAtHead (self, val: int ) -> None : self.addAtIndex(0 , val) def addAtTail (self, val: int ) -> None : self.addAtIndex(self.size, val) def addAtIndex (self, index: int , val: int ) -> None : if index < 0 : index = 0 elif index > self.size: return pre = self.dummy i = 0 while i < index: pre = pre.next i += 1 pre.next = ListNode(val, pre.next ) self.size += 1 return def deleteAtIndex (self, index: int ) -> None : if index < 0 or index >= self.size: return pre = self.dummy i = 0 while i < index: pre = pre.next i += 1 pre.next = pre.next .next self.size -= 1 return
第二题 876. 链表的中间结点 - 力扣(LeetCode)
代码 python版本
1 2 3 4 5 6 7 8 class Solution : def middleNode (self, head: Optional [ListNode] ) -> Optional [ListNode]: slow = fast = head while fast and fast.next : fast = fast.next .next slow = slow.next return slow
第三题 203. 移除链表元素 - 力扣(LeetCode)
代码 python版本
1 2 3 4 5 6 7 8 9 10 class Solution : def removeElements (self, head: Optional [ListNode], val: int ) -> Optional [ListNode]: dummy = ListNode(-1 , head) cur = dummy while cur.next : if cur.next .val == val: cur.next = cur.next .next else : cur = cur.next return dummy.next
第四题 83. 删除排序链表中的重复元素 - 力扣(LeetCode)
代码 python版本
1 2 3 4 5 6 7 8 9 10 11 class Solution : def deleteDuplicates (self, head: Optional [ListNode] ) -> Optional [ListNode]: dummy = ListNode(-101 , head) cur = dummy while cur.next : if cur.val == cur.next .val: cur.next = cur.next .next else : cur = cur.next return dummy.next
第五题 19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
代码 python版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution : def removeNthFromEnd (self, head: Optional [ListNode], n: int ) -> Optional [ListNode]: dummy = ListNode(-1 , head) slow = fast = dummy i = 0 while i < n: fast = fast.next i += 1 while fast.next : fast = fast.next slow = slow.next slow.next = slow.next .next return dummy.next