Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively.
/**
* 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* p = NULL;
ListNode* q = NULL;
while (head)
{
//ListNode* q = head -> next;
q = head -> next;
head -> next = p;
p = head;
head = q;
}
return p;
}
};