反转链表的两种方法,虽然递归法比较复杂而且更加浪费空间一点,但是记录一下说不定以后就能用到~~
迭代法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//iteratively
ListNode h=ListNode(-1);//头结点
while(head!=NULL)
{
ListNode *p=head;
head=head->next;
p->next=h.next;
h.next=p;
}
return h.next;
}
};
递归法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//recursively
if(head==NULL||head->next==NULL)
return head;
ListNode *tmp=head->next;
ListNode *newHead=reverseList(head->next);
tmp->next=head;
head->next=NULL;
return newHead;
}
};