剑指Offer--15.反转链表

来源:互联网 发布:wap积分兑换商城源码 编辑:程序博客网 时间:2024/06/03 21:40

题目描述:

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

python代码:

# -*- 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 or pHead.next == None:            return pHead        p_head = ListNode(0)        while pHead:            pNext = pHead            pHead = pHead.next            pNext.next = p_head.next            p_head.next = pNext        return p_head.next

解析:

本题的实现中使用了一个头节点p_head,每次将pHead(剩余链表中的第一个节点)插入头结点后面。最终pHead指向空时返回p_head的下一个节点即可返回翻转的链表。

原创粉丝点击