原文地址:https://www.jianshu.com/p/5621f95b0115

时间限制:1秒 空间限制:32768K

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

我的代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==nullptr || pHead->next==nullptr)
            return pHead;
        ListNode* cur=pHead;
        ListNode* pre=nullptr;
        ListNode* save=nullptr;
        ListNode* reverseHead=nullptr;
        while(cur){
            save=cur->next;
            cur->next=pre;
            if(save==nullptr)
                reverseHead=cur;
            pre=cur;
            cur=save;
        }
        return reverseHead;
    }
};

运行时间:4ms
占用内存:380k

相关文章:

  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-26
  • 2021-09-25
  • 2021-04-11
猜你喜欢
  • 2022-12-23
  • 2021-12-26
  • 2021-12-02
  • 2021-05-23
相关资源
相似解决方案