Reverse a singly linked list.
Subscribe to see which companies asked this question
/**
* 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)
{
if(!head)
return NULL;
if(!head->next)
return head;
ListNode* x=head;
ListNode* y=x->next;
x->next=NULL;
while(y->next)
{
ListNode*z=y->next;
y->next=x;
x=y;
y=z;
}
y->next=x;
head=y;
return head;
}
};