1. 程式人生 > >劍指offer15.反轉連結串列

劍指offer15.反轉連結串列

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

題目描述
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。

先用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