题目描述:
输入一个链表,反转链表后,输出链表的所有元素。
python代码:
# -*- 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 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的下一个节点即可返回翻转的链表。