Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
单链表的原地逆置,需要记录三个数据,当前节点、前一个节点、后一个节点。
/**
* 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;
ListNode* pre;
ListNode* cur;
ListNode* next;
pre=NULL;
cur=head;
while(cur->next!=NULL)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
cur->next=pre;
return cur;
}
};