203. Remove Linked List Elements
这道题设置一个虚拟节点比较方便,否则需要单独处理头节点。
# 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]:
# Set a virtual head node
tmpNode = ListNode()
tmpNode.next = head
p = tmpNode
while p.next != None:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return tmpNode.next
707. Design Linked List
第一次交的时候没有过,原因是忘记delete时count -= 1
class Node:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self.head = Node(0) # virtual haed node
self.count = 0 # number of node added
def get(self, index: int) -> int:
if 0 <= index < self.count:
p = self.head.next
for _ in range(index):
p = p.next
return p.val
else:
return -1
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.count, val)
def addAtIndex(self, index: int, val: int) -> None:
if 0 <= index <= self.count:
p = self.head
for _ in range(index):
p = p.next
newNode = Node(val)
newNode.next = p.next
p.next = newNode
self.count += 1
else:
return
def deleteAtIndex(self, index: int) -> None:
if 0 <= index < self.count:
p = self.head
for _ in range(index):
p = p.next
p.next = p.next.next
self.count -= 1
else:
return
# 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. Reverse Linked List
双指针
首先定义一个cur指针,指向头结点,再定义一个pre指针,初始化为null。
然后就要开始反转了,首先要把 cur->next 节点用tmp指针保存一下,也就是保存一下这个节点。
接下来,就是循环走如下代码逻辑了,继续移动pre和cur指针。
# 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]:
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
递归法
if cur == None
是递归的出口,即pre
移动到了链表尾部
# 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]:
def reverse(pre, cur):
if cur == None:
return pre
tmp = cur.next
cur.next = pre
# 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了
# pre = cur
# cur = tmp
return reverse(cur, tmp)
return reverse(None, head)