欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python3實(shí)現(xiàn)的反轉(zhuǎn)單鏈表算法示例

 更新時(shí)間:2019年03月08日 09:15:34   作者:zhenghaitian  
這篇文章主要介紹了Python3實(shí)現(xiàn)的反轉(zhuǎn)單鏈表算法,結(jié)合實(shí)例形式總結(jié)分析了Python基于迭代算法與遞歸算法實(shí)現(xiàn)的翻轉(zhuǎn)單鏈表相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python3實(shí)現(xiàn)的反轉(zhuǎn)單鏈表算法。分享給大家供大家參考,具體如下:

反轉(zhuǎn)一個(gè)單鏈表。

方案一:迭代

# Definition for singly-linked list.
# class ListNode:
#   def __init__(self, x):
#     self.val = x
#     self.next = None
class Solution:
  def reverseList(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    cur, pre = head, None
    while cur:
      cur.next, pre, cur = pre, cur, cur.next
    return pre

方案二:遞歸

# -*- 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 or not pHead.next:
      return pHead
    else:
      newHead = self.ReverseList(pHead.next)
      pHead.next.next=pHead
      pHead.next=None
      return newHead

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論