解题思路:定义一个链表节点node为nullptr,一个temp节点来存储head->next,让head->next=node,更新node的值为head,head的值为temp,让head结点循环向后遍历,直到head节点为空,此时的node就是反转后链表的头节点
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* node=nullptr;
while(head!=nullptr){
ListNode* temp=head->next;
head->next=node;
node=head;
head=temp;
}
return node;
}
};