【剑指offer】面试题 24:反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

时间限制:1秒 空间限制:32768K 热度指数:137078
本题知识点: 链表


思路

pHead始终指向要反转的节点,last 指向反转后的首节点,

每反转一个节点,把 pHead 节点的下一个节点指向 last,

last 指向 pHead 成为反转后的首节点,再把 pHead 向前移动一个节点直至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
        if not pHead or not pHead.next:
            return pHead
        
        last = None
        
        while pHead:
            tmp = pHead.next
            pHead.next = last
            last = pHead
            pHead = tmp
        
        return last


版本二

# -*- 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
        pReversedHead = None
        pNode = pHead
        pPrev = None
        while pNode != None:
            pNext = pNode.next
            
            if pNext == None:
                pReversedHead = pNode
                
            pNode.next = pPrev
            pPrev = pNode
            pNode = pNext
        return pReversedHead
    
    def ReverseListRec(self, pHead):
        if not pHead or not pHead.next:
            return pHead
        else:
            pReversedHead = self.ReversedList(pHead.next)
            pHead.next.next = pHead
            pHead.next = None
            return pReversedHead










你可能感兴趣的:(剑指offer,剑指offer)