203.移除链表元素
由于博主之前就学习过此类内容,所以感觉并没有太多难的地方。最关键的点还是在于虚拟头节点的建立会让后面的操作更舒服一些。
# 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=ListNode(0)
dummy.next=head
pre=dummy;cur=head
while cur is not None:
if cur.val == val:
cur=cur.next
pre.next=pre.next.next
else:
cur=cur.next
pre=pre.next
return dummy.next
707.设计链表
设计链表问题不算特别困难,但是也有很多小细节需要注意。
首先,要先创建一个节点类并初始化。然后才是链表类的创建。
对于链表类,需要注意,添加节点和删除节点都需要记得改变节点的size。
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class MyLinkedList:
def __init__(self):
self.dummy_head=ListNode()
self.size=0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur=self.dummy_head.next
for i in range(index):
cur=cur.next
return cur.val
def addAtHead(self, val: int) -> None:
new_head=ListNode(val)
new_head.next=self.dummy_head.next
self.dummy_head.next=new_head
self.size+=1
def addAtTail(self, val: int) -> None:
tail_head=ListNode(val)
cur=self.dummy_head
while cur.next is not None:
cur=cur.next
cur.next=tail_head
self.size+=1
def addAtIndex(self, index: int, val: int) -> None:
if index<0 or index>self.size:
return
cur=self.dummy_head
r_node=ListNode(val)
for i in range(index):
cur=cur.next
r_node.next=cur.next
cur.next=r_node
self.size+=1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
cur=self.dummy_head
for i in range(index):
cur=cur.next
cur.next=cur.next.next
self.size-=1
206.反转链表
反转链表操作最重要的清楚反转逻辑。
定义两个指针cur和pre.分别指向头节点和null。实例化一个临时指针tmp指向cur.next。
之后就要开始反转链表了。先将cur.next指向pre.然后向后移动cur和pre(pre=cur,cur=tmp)。循环如此
# 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]:
cur,pre=head,None
while cur:
temp=cur.next #temp暂存后继节点
cur.next=pre #cur执行反向指向操作指向pre/断开指针,转而指向None
pre=cur #pre向后移动,即把cur指针赋给pre
cur=temp #cur向后移动,使用temp暂存的后继节点
return pre