反轉鏈表--原地反轉

題目描述:輸入一個鏈表,反轉鏈表後,輸出新鏈表

鏈表與數組不同,每個結點除數據區外,還存在一個指針區,用來存放下一個結點的地址。
因此,單鏈表的訪問只能從頭開始訪問。
在對鏈表操作中,需要注意修改結點指針區時,需要記錄下來後繼結點的位置,否則會丟失後繼結點。

方法:就地逆序
給定鏈表 1-->2-->3-->4-->5-->None
反轉鏈表 5-->4-->3-->2-->1-->None

思路:
圖片描述

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

這麼寫,程序會報錯。錯誤提示:

您的代碼已保存
答案錯誤:您提交的程序沒有通過所有的測試用例
case通過率爲66.67%

用例:
{}
對應輸出應該爲:
{}

你的輸出爲:
'NoneType' object has no attribute 'next'

可以看出當鏈表爲空時,cur.next 不存在,改進代碼

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

clipboard.png

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