203.移除链表元素
题目链接
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
自己代码
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(next = head)
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
注意设置虚拟头节点,并且最终返回虚拟头的下一个
707.设计链表
代码随想录
class Node:
def __init__(self,val = 0,next = None):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self, size = 0):
self.size = size
self.dummy_head = Node()
def get(self, index: int) -> int:
if index<0 or index > self.size-1:
return -1
cur = self.dummy_head.next
while index > 0 :
index -= 1
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
newnode = Node(val)
newnode.next = self.dummy_head.next
self.dummy_head.next = newnode
self.size += 1
def addAtTail(self, val: int) -> None:
cur = self.dummy_head
while cur.next:
cur = cur.next
cur.next = Node(val)
self.size+=1
def addAtIndex(self, index: int, val: int) -> None:
if index <0 :
self.addAtHead(val)
return
if index == self.size :
self.addAtTail(val)
return
if index > self.size:
return
newnode = Node(val)
cur = self.dummy_head
while index>0:
index -= 1
cur = cur.next
newnode.next = cur.next
cur.next = newnode
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index <0 or index > self.size-1:
return
else:
cur = self.dummy_head
while index>0:
index -= 1
cur = cur.next
cur.next = cur.next.next
self.size -= 1
反转链表
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
自己代码
双指针写法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
注意:需要tmp存储cur.next,需要前后两个指针
代码随想录
需要学习下递归法
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(pre,cur):
if not cur:
return pre
tmp = cur.next
cur.next = pre
return reverse(cur,tmp)
return reverse(None,head)