牛客網《劍指offer》之Python2.7實現:反轉連結串列
阿新 • • 發佈:2018-12-12
題目描述
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。
思路
迴圈遍歷連結串列,一邊遍歷,一邊構建新的逆序連結串列
程式碼
# -*- 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 re = ListNode(pHead.val) while pHead.next != None: pHead = pHead.next temp = ListNode(pHead.val) temp.next = re re = temp return re