移除链表元素
思路:增加虚拟头节点,实现第一个节点就是目标值的情况
实现思路一开始想用两层while循环嵌套,第一层判断下一个节点不为空,第二层while 实现连续的目标值删除,但是报错了,由于时间紧张,先放下,回头再研究为什么不行
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dumpy_head=ListNode()
dumpy_head.next=head
curr=dumpy_head
while curr.next:
if curr.next.val==val:
curr.next=curr.next.next
else:
curr=curr.next
return dumpy_head.next
707.设计链表
敲代码的时候,一个逗号用了中文字符,找了半天bug ,最后还是文心一言找的,绝了
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):
"""
:type index: int
:rtype: int
"""
if index<0 or index>=self.size:
return -1
curr=self.dummy_head.next
for i in range(index):
curr=curr.next
return curr.val
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
self.dummy_head.next=ListNode(val,self.dummy_head.next)
self.size+=1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
curr=self.dummy_head
while curr.next:
curr=curr.next
curr.next=ListNode(val)
self.size+=1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index >self.size or index <0:
return
curr=self.dummy_head
for i in range(index):
curr=curr.next
curr.next=ListNode(val,curr.next)
self.size+=1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index>=self.size or index<0:
return
curr=self.dummy_head
for i in range(index):
curr=curr.next
curr.next=curr.next.next
self.size-=1
# 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.反转链表
思路:双指针,定义一个指针指向前一个节点,临时节点保存当前指针,然后当前指针的下一个指向前一个节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre=None
cur=head
while cur:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre