问题:输入一个链表,反转链表后,输出新链表的表头。
对于反转链表的问题还是非常简单的,首先我们生成一个尾部的结点,然后从链表的头部逐个生成新节点,将生成的新节点放到尾部的终点之前,不断的重复,直到所有的链表的结点都结束。
代码如下:
# -*- 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
new = None
pHead_j = pHead
while pHead_j:
temp = ListNode(pHead_j.val)
temp.next = new
new = temp
pHead_j = pHead_j.next
return new