劍指offer-反轉鏈表

輸入一個鏈表,反轉鏈表後,輸出鏈表的全部元素。spa

#-*- 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 not pHead:
            return None
        pre = None
        while pHead:
            current = pHead
            pHead = pHead.next
            current.next = pre
            pre = current
        return current

思路,三個指針,current表示當前指針,pre前指針,後指針。經過各自複製,將current.next = pre後,各自向後移動直到鏈表爲空,返回current即倒序後的頭指針。指針

相關文章
相關標籤/搜索