剑指offer 16 反转链表

来源:互联网 发布:双系统ubuntu安装教程 编辑:程序博客网 时间:2024/05/19 12:27

题目描述
输入一个链表,反转链表后,输出链表的所有元素。
思路:
从头到尾遍历,把每个结点反向指过来。

# -*- coding:utf-8 -*-# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # 返回ListNode    def ReverseList(self, pHead):        # write code here        if pHead == None:            return None        pTail = None        res = None        while pHead != None:            pNext = pHead.next            if pNext == None:                res = pHead            pHead.next = pTail            pTail = pHead            pHead = pNext        return res
原创粉丝点击