码迷,mamicode.com
首页 > 编程语言 > 详细

剑指offer反转链表python

时间:2019-11-04 12:00:05      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:lis   content   reverse   init   code   none   color   list   node   

题目描述

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

思路

定义三个指针,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

 

剑指offer反转链表python

标签:lis   content   reverse   init   code   none   color   list   node   

原文地址:https://www.cnblogs.com/wangzhihang/p/11790769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!