Reverse a singly linked list.
1、迭代法
遍历该单链表,将节点一个一个摘下来,采用 头插法 插入另一条链表:
/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head){
ListNode node(0);
ListNode* L=&node;
while(head!=NULL){
ListNode *q=head->next;
head->next=L->next;
L->next=head;
head=q;
}
return L->next;
}
};