面试题24:反转链表
Posted ivyharding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试题24:反转链表相关的知识,希望对你有一定的参考价值。
这道题感觉很难,还没有理解
几天后:
# -*- 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 # 1.将现有的头换成尾,尾部的next为空 # 2.将从第二个node开始,循环将next指向前一个 # 3.需要有一个指针一直指向还没有反转的链表的表头 if pHead == None: return None if pHead.next == None: return pHead leftpointer = pHead midpointer = pHead.next rightpointer = midpointer.next leftpointer.next = None while rightpointer != None: midpointer.next = leftpointer leftpointer = midpointer midpointer = rightpointer rightpointer = rightpointer.next midpointer.next = leftpointer return midpointer
以上是关于面试题24:反转链表的主要内容,如果未能解决你的问题,请参考以下文章