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

#-*- 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即倒序后的头指针。

相关文章:

  • 2021-08-13
  • 2021-09-12
  • 2021-05-04
  • 2021-09-04
  • 2022-01-10
  • 2021-09-17
猜你喜欢
  • 2021-12-18
  • 2021-10-25
  • 2021-08-19
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
相关资源
相似解决方案