剑指offer——反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。
这个题目有两种写法,非递归和递归的写法,我们先说非递归的写法,,设计三个指针,pre,cur还有post,代码里面用a、b、c分别来表示,依次迭代反转。
# -*- 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 pHead==None:
            return None
        a=pHead
        b=pHead.next
        a.next=None
        while b :
            c=b.next
            b.next=a
            a=b
            b=c
        return a
            

 另外一种递归的写法,其实就是把非递归的三个指针封装起来进行递归。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def func(self,pre,cur,post):
        if post==None:
            cur.next=pre
            return cur
        else:
            cur.next=pre
            pre=cur
            cur=post
            post=post.next
            return self.func(pre,cur,post)
    def ReverseList(self, pHead):
        # write code here
        if pHead==None:
            return None
        else:
            pre=None
            return self.func(pre,pHead,pHead.next)
        
        

  

原文地址:https://www.cnblogs.com/hit-joseph/p/9523224.html