面试24题:

题目:反转链表

题:输入一个链表,反转链表并输出反转后链表的头节点。

解题思路:注意反转时出现断裂现象,定义3个指针,分别指向当前遍历到的节点pNode、它的前一个节点pPrev及后一个节点pNext。

解题代码:

# -*- 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
        pReversedHead=None
        pNode=pHead
        pPrev=None
        while pNode:
            pNext=pNode.next
            if not pNext:
                pReversedHead=pNode
            pNode.next=pPrev
            pPrev=pNode
            pNode=pNext
        return pReversedHead

 

相关文章:

  • 2022-02-26
  • 2021-09-06
  • 2021-12-23
  • 2021-09-20
  • 2021-09-29
  • 2021-09-21
  • 2022-01-25
  • 2022-02-20
猜你喜欢
  • 2021-12-19
  • 2021-07-23
  • 2021-09-13
  • 2021-11-03
  • 2021-09-20
  • 2021-07-09
  • 2021-12-13
相关资源
相似解决方案