思路
建立哨兵节点,遍历每个节点 使用 while if else结构来遍历节点,没写出来
代码
# 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]:
cur=dummy=ListNode(next=head)
while cur.next:
if cur.next.val==val:
cur.next=cur.next.next
else:
cur=cur.next
return dummy.next
707
思路:不会写.主要学习添加节点和删除节点。使用哨兵节点来添加和删除节点方便
代码
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class MyLinkedList:
def __init__(self):
self.size=0
self.dummy_head=ListNode()
def get(self, index: int) -> int:
if index<0 or index>=self.size:
return -1
cur=self.dummy_head
for _ in range(index+1):
cur=cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.addAtIndex(0,val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.size,val)
def addAtIndex(self, index: int, val: int) -> None:
if index<0 or index>self.size:
return
cur=self.dummy_head
for i in range(index):
cur=cur.next
cur.next=ListNode(val,cur.next)
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
# 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
思路
使用pre,nxt,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]:
cur=head
pre=None
while cur:
nxt=cur.next
cur.next=pre
pre=cur
cur=nxt
return pre