206.反转链表 (容易考,容易忘)
作者:互联网
problems/0206.翻转链表.md · programmercarl/leetcode-master(代码随想录出品) - Gitee.com
比较简单,但是很久没做第一次用的算法也比较粗糙:
不算太好的解法,时间复杂度N^2(先遍历到最后一个节点用指针p标记,同时标记其为头结点,循环:再用另一个指针q标记指向它的指针,p指向q,q置空,p指向q,重复以上步骤)
点击查看代码
# 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: ListNode) -> ListNode:
if head is None:
return None
virtual_head = ListNode()
virtual_head.next = head
current = virtual_head
p = head
while p.next is not None:
p = p.next
virtual_head.next = p
q = head
while head.next is not None:
while q.next is not p:
q = q.next
q.next = None
p.next = q
p = p.next
q = head
return virtual_head.next
最佳解法还是双指针翻转法,用到了三个临时指针
点击查看代码
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p = head
q = None
while p is not None:
temp_node = p.next
p.next = q
q = p
p = temp_node
return q
标签:head,ListNode,206,self,None,virtual,next,链表,容易 来源: https://www.cnblogs.com/Linanjing/p/16411613.html