方法一:构建一个栈
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* ReverseList(ListNode* head) {
// write code here
stack<ListNode*>stc;
ListNode* t = head;
//注意判空
if(t==NULL)return NULL;
while(t!=NULL)
{
stc.push(t);
t = t->next;
}
//nlist:反转后的新链表
//tem:存储临时的节点
//rhead:用以一个一个结点构建链表
ListNode* rhead = stc.top();
ListNode* nlist = rhead;
stc.pop();
while(!stc.empty())
{
ListNode* tem;
tem = stc.top();
stc.pop();
rhead->next = tem;
rhead = rhead->next;
}
rhead->next = NULL;
return nlist;
}
};



京公网安备 11010502036488号