203. 移除链表元素
链表好久不碰还真有点忘了,这题debug了大约15分钟,记录一下犯的错误:
1. cur.next如果要删除,cur在这个循环中不应该向后移动,否则会影响循环不变式,跳过某些要删的元素。
2. 返回应该返回dummy_head.next而不是head
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy_head = ListNode(0)
dummy_head.next = head
cur = dummy_head
while cur.next != None:
if cur.next.val == val:
tmp = cur.next.next
cur.next.next = None
cur.next = tmp
else:
cur = cur.next
return dummy_head.next
707.设计链表
这题一刷没做出来,二刷突然就开窍了...感觉这一年代码不是白写的...
没啥好说的,新建链表类实际新建虚拟头节点。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummy_head = ListNode(0)
def get(self, index: int) -> int:
if index < 0:
return -1
cur = self.dummy_head
for i in range(index + 1):
if cur.next != None:
cur = cur.next
else:
return -1
return cur.val
def addAtHead(self, val: int) -> None:
tmp = ListNode(val)
tmp.next = self.dummy_head.next
self.dummy_head.next = tmp
def addAtTail(self, val: int) -> None:
cur = self.dummy_head
tmp = ListNode(val)
while cur.next != None:
cur = cur.next
cur.next = tmp
def addAtIndex(self, index: int, val: int) -> None:
if index < 0:
return
cur = self.dummy_head
for i in range(index):
if cur.next != None:
cur = cur.next
else:
return
tmp = ListNode(val)
tmp.next = cur.next
cur.next = tmp
def deleteAtIndex(self, index: int) -> None:
if index < 0:
return
cur = self.dummy_head
for i in range(index):
if cur.next != None:
cur = cur.next
else:
return
if cur.next != None:
cur.next = cur.next.next
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
206.反转链表
双指针实现比较简单,左指针指向反转好的新头节点,右指针指向还没翻转链表的的头节点,只需要保存右指针的next,将右指针指向的节点指到左指针指向的节点即可。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow, fast = None, head
while fast != None:
tmp = fast.next
fast.next = slow
slow = fast
fast = tmp
return slow
递归法比较难想明白,这里有头递归和尾递归两种写法,尾递归就是双指针;头递归则是递归返回时从后向前翻转。
头递归方法:
1. 终止条件:head是None,返回None, 处理空链表;head.next是None,这里给出新头节点。
2. 每一层递归调用栈中的new_head均是处理好的新链表的头节点,每层递归调用栈处于如下状态:
递归调用栈中的head → 本层栈中head → 翻转完成的链表尾节点 ← ... ← 新头节点
↓
None
于是只需要让head.next.next指向head, head.next指向None即可返回到上一层递归调用栈。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return None
if head.next == None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
783

被折叠的 条评论
为什么被折叠?



