class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy_head = ListNode(next = head)
# 遍历列表并删除值为val的节点
current = dummy_head
while current.next:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return dummy_head.next
第一题很简单,虚拟头结点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList(object):
def __init__(self):
self.dummy_head=ListNode()
self.size=0
def get(self, index):
"""
:type index: int
:rtype: int
"""
cur=self.dummy_head
if index>=0 and index<self.size:
while index>=0:
cur=cur.next
index-=1
return cur.val
else:
return -1
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
"""
cur=self.dummy_head
while cur.next:
cur=cur.next
cur.next=ListNode(val,None)
self.size+=1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
cur=self.dummy_head
if index>=0 and index<=self.size:
while index>0:
cur=cur.next
index-=1
cur.next=ListNode(val,cur.next)
self.size+=1
else:
return
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
cur=self.dummy_head
if index>=0 and index<self.size:
while index>0:
cur=cur.next
index-=1
cur.next=cur.next.next
self.size-=1
else:
return
第二题,只要初始化成功,逻辑也不
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre=ListNode(next=head)
cur=head
if head==None:
return None
while cur:
cur1=cur.next
cur.next=pre
pre=cur
cur=cur1
head.next=None
return pre
翻转链表这题想了很久,看了动画终于理清思路,但也不知道总结啥,唉,这题以前做过,时间长了忘了又不会了