描述
输入一个长度为n链表,反转链表后,输出新链表的表头。
数据范围 nleq1000n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead is None:
return None
pre = None
cur = pHead
nxt = None
while cur != None:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
思路:遍历链表,临时保存现在节点的next和前一个节点,然后将现在节点的next指向前一个节点,而用临时保存的下一个节点继续向后遍历,直到遍历到最后的节点,将其next指向head。



