【面試題24】反轉鏈表

這道題之前做過,但是忘的一乾二淨,這裏再寫一遍。

206.反轉鏈表

92.反轉鏈表Ⅱ

在這裏插入圖片描述
Python題解

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead or not pHead.next:return pHead
        
        pre, cur, reversedHead = None, pHead, None
        while cur != None:
            nxt = cur.next
            if nxt == None:
                reversedHead = cur
            cur.next = pre
            pre = cur
            cur = nxt
        return reversedHead

考點

  • 考查對鏈表,指針的編程能力;
  • 考查思維的全面性和代碼的魯棒性。

擴展

用遞歸實現同樣的反轉鏈表的功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章