Reverse a singly linked list.
思路
链表反转。有递归和非递归两种方法。在前面一篇文章《链表操作》中已经有介绍,这里就不多说了。
代码(C++)
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if (NULL == head || NULL == head->next)
return head;
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* nx;
while (cur != NULL)
{
nx = cur->next;
cur->next = pre;
pre = cur;
cur = nx;
}
head->next = NULL;
head = pre;
return head;
}
};