DAY 3 链表
203.移除链表元素
题目
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
思路
链表的头节点和其余节点的的删除方式不一致,根据是否使用虚拟头节点可以有两种方法。
方法一、不使用虚拟头节点
代码如下:
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
#不设置虚拟头节点
#判断头节点是否为空及值是否等于目标
while head and head.val == val:
head = head.next #移除头指针指向的元素
cur = head
while cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
方法二、使用虚拟头节点
代码如下
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
#设置虚拟头节点
dummy = ListNode(next = head) #创建一个虚拟头节点
cur_head = dummy
while cur_head.next: #遍历列表删除满足的节点
if cur_head.next.val == val:
cur_head.next = cur_head.next.next
else :
cur_head = cur_head.next
return dummy.next
206. 反转链表
题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
思路
定义一个新的链表,实现链表元素的反转,是对内存空间的浪费。其实只需要改变链表的next指针的指向,直接将链表反转 ,而不用重新定义一个新的链表。
两种写法,双指针法和递归写法,但实际上递归写法是建立在前者的基础上,要重点掌握双指针法。
# 双指针写法 要熟练掌握
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = None #定义反转过后的最后的空指针
cur = head
while cur:
temp = cur.next #存储,用来记录下一次反转的指针
cur.next = pre #指针反转
#进行下两个值的反转
pre = cur
cur = temp
return pre
#递归写法
class Solution(object):
def reverseList(self, head):
return self.reverse(head,None)
def reverse(self,cur,pre):
if cur == None:
return pre
temp = cur.next
cur.next = pre
return self.reverse(temp,cur)