剑指offer反转链表python

题目描述

输入一个链表,反转链表后,输出新链表的表头。
 

思路

定义三个指针,pHead, cur,forward

反转的时候,cur.next指向pHead,然后三个指针依次向后移动,具体过程看代码。

代码

# -*- 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
        current = pHead.next
        forward = current.next
        pHead.next = None
        while current:
            current.next = pHead
            pHead = current
            current = forward
            if forward:
                forward = forward.next
        return pHead

相关推荐