這道題之前做過,但是忘的一乾二淨,這裏再寫一遍。
Python題解
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead or not pHead.next:return pHead
pre, cur, reversedHead = None, pHead, None
while cur != None:
nxt = cur.next
if nxt == None:
reversedHead = cur
cur.next = pre
pre = cur
cur = nxt
return reversedHead
考點
- 考查對鏈表,指針的編程能力;
- 考查思維的全面性和代碼的魯棒性。
擴展
用遞歸實現同樣的反轉鏈表的功能。