題目
輸入一個鏈表,反轉鏈表后,輸出鏈表的所有元素。
思路
遍歷鏈表,將每個節點的next指向其前一個節點,頭節點則指向None
代碼
# -*- 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
cur = pHead
pre = None
#if pHead:
# cur = cur.next
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
收獲
涉及到數組,鏈表這一類問題,盡可能移動指針,而不要移動元素,因為元素可能會很大。