劍指offer15.反轉連結串列
阿新 • • 發佈:2019-01-05
題目描述
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。
先用tmp儲存head.next,然後將head插入res後面,最後將tmp賦值給head:
# -*- 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 res = ListNode(0) while pHead: tmp = pHead.next pHead.next = res.next res.next = pHead pHead = tmp return res.next