输入一个链表,反转链表后,输出链表的所有元素。
#-*- 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 not pHead: return None pre = None while pHead: current = pHead pHead = pHead.next current.next = pre pre = current return current
思路,三个指针,current表示当前指针,pre前指针,后指针。通过各自复制,将current.next = pre后,各自向后移动直到链表为空,返回current即倒序后的头指针。