Leetcodeブラッシングレコード-206。リバースリンクリスト

ここに画像の説明を挿入
2回の反復と再帰を実装しました。
問題は比較的単純です。
元のリンクリストは
1-> 2-> 3-> 4-> 5-> NULLであり
、操作後は
5-> 4-> 3-> 2-> 1-> NULLです。
この質問に注意してください:元の入力ノードの次を[なし]に設定することを忘れないでください

反復:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None:
            return [] 
        
        thisstack = []
        print(thisstack)
        while  True:#head is not None:
            thisstack.append(head)
            #print(head.val)
            if head.next is not None:
                head = head.next#thisstack[-1]
            else:
                break
        #print(thisstack)
        tempnode = head#tempnode
        while thisstack != []:
            tempnode.next = thisstack.pop(-1)
            tempnode = tempnode.next
        tempnode.next = None
        return head

再帰:

class Solution:
    def __init__(self):
        self.newhead = None
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None:
            return [] 
        self.func(head)
        head.next = None
        return self.newhead
    def func(self,node):
        if  node.next is not None:
            self.func(node.next)
            node.next.next = node
        else:
            self.newhead = node

43件の元の記事を公開 14 件を賞賛・2 万回以上の閲覧

おすすめ

転載: blog.csdn.net/weixin_41545780/article/details/105330135
おすすめ