题目描述

输入一个链表,反转链表后,输出新链表的表头。

解题思路

定义2个辅助节点:

  • 上一个节点
  • 下一个节点
完整代码
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == nullptr)
            return nullptr;
        
        ListNode* pNode = pHead;
        ListNode* pReverse = nullptr;
        ListNode* pPrev = nullptr;
        ListNode* pNext = nullptr;
        while(pNode != nullptr){
            // 保留下一个节点
            pNext = pNode->next;
            if(pNext == nullptr)
                pReverse = pNode;
            pNode->next = pPrev;
            pPrev = pNode;
            pNode = pNext;
        }
        return pReverse;
    }
};

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2022-01-09
  • 2021-09-09
  • 2021-04-28
  • 2021-11-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2021-11-25
相关资源
相似解决方案