C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL){
return NULL;
}
struct ListNode* n=NULL,*c=NULL,*p=NULL;
c=head;
while(c!=NULL){
n=c->next;
c->next=p;
p=c;
c=n;
}
return p;
}
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr){
return nullptr;
}
ListNode* n=nullptr,*c=nullptr,*p=nullptr;
c=head;
while(c!=nullptr){
n=c->next;
c->next=p;
p=c;
c=n;
}
return p;
}
};