Reverse a singly linked list.
/**
* 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 == NULL || head->next == NULL)
return head;
if(head->next->next == NULL)
{
ListNode* newhead = head->next;
newhead->next = head;
head->next = NULL;
return newhead;
}
ListNode* Prev = head;
ListNode* pNode = head->next;
Prev->next = NULL;
ListNode* pTail = pNode->next;
while(pNode->next!=NULL)
{
pNode ->next = Prev;
Prev = pNode;
pNode = pTail;
pTail = pTail->next;
}
pNode ->next = Prev;
return pNode;
}
};