image.png
這個題是面試中的郴吐瑁考題儡羔,在作業(yè)幫的面試中也遇到了,面試官要求手寫代碼璧诵。
首先要記住的是:要有三個指針汰蜘, 分別是prev,cur,temp。
prev指針來記錄前一個節(jié)點之宿,cur是當前的指針族操,temp中存儲的是當前節(jié)點的下一個節(jié)點,然后將cur中的next指向prev,然后cur和prev前進一步比被。直到尾端色难。
一個要點:如果當前是空鏈表,則返回空鏈表等缀。所以將prev初始化為none枷莉,最后也返回prev
# -*- 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
prev = None
cur = pHead
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev