Reverse a singly linked list.
Recursion:
<pre name="code" class="cpp">/**
* 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) return NULL;
if(head->next==NULL) return head;
ListNode *p=head->next;
ListNode *n=reverseList(p);
head->next=NULL;
p->next=head;
return n;//return n把n最后一个链表值作为头返回
}
};
Non-recursion:
<pre name="code" class="cpp">/**
* 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;//递归的效率低,所以不要用递归
ListNode *pre=head;
ListNode *p=pre->next;
pre->next=NULL;
ListNode *t;
while(p!=NULL)
{
t = p->next;
p->next=pre;
pre = p;
p = t;
}
return pre;//最后一个pre是最后一个值
}
};