1. 程式人生 > 實用技巧 >.net framework 4.5 asp.net api 使用 swagger

.net framework 4.5 asp.net api 使用 swagger

定義一個函式,輸入一個連結串列的頭節點,反轉該連結串列並輸出反轉後連結串列的頭節點。

輸入: 1->2->3->4->5->NULL輸出: 5->4->3->2->1->NULL

雙指標:定義兩個指標,pre指向空,cur指向頭節點,然後不斷遍歷cur,將 cur 的 next 指向 pre,然後 pre 和 cur 前進一位。

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        
""" pre, cur = None,head while cur: tmp = cur.next cur.next = pre pre, cur = cur,tmp return pre

迭代法:終止條件是當前節點或者下一個節點==null在函式內部,改變節點的指向,也就是 head 的下一個節點指向 head 遞迴函式那句

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        
""" # 遞迴終止條件是當前為空,或者下一個節點為空 if(head==None or head.next==None): return head # 這裡的cur就是最後一個節點 cur = self.reverseList(head.next) # 這裡請配合動畫演示理解 # 如果連結串列是 1->2->3->4->5,那麼此時的cur就是5 # 而head是4,head的下一個是5,下下一個是空 # 所以head.next.next 就是5->4
head.next.next = head # 防止連結串列迴圈,需要將head.next設定為空 head.next = None # 每層遞迴函式都返回cur,也就是最後一個節點 return cur 作者:wang_ni_ma 連結:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/dong-hua-yan-shi-duo-chong-jie-fa-206-fan-zhuan-li/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。