剑指offer----链表(二):反转链表

xiaoxiao2021-02-28  55

题目描述:输入一个链表,反转链表后,输出链表的所有元素。

思路:定义3

个指针,分别指向当前遍历到的结点、它的前一个结点及后一个结点。

测试用例分析:输入的链表头指针是nullptr,输入的链表只有一个结点,输入的链表有多个结点。

代码:

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 not pHead or not pHead.next: return pHead ListNode = None while pHead: t = pHead.next pHead.next = ListNode ListNode = pHead pHead = t return ListNode

C/C++版:

转载请注明原文地址: https://www.6miu.com/read-2626173.html

最新回复(0)