22.leetcode题目206: Reverse Linked List

题目:

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

分析:

翻转链表。

根据提示:方法一,依次翻转

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
     <span style="color:#006600;">   //reversed iteratively</span><span style="color:#ffff00;">
</span>        if(head==NULL){
            return head;
        }
        ListNode* res=head;
        ListNode* p=res->next;
        res->next=NULL;
        while(p!=NULL){
            ListNode* q=p->next;
            p->next=res;
            res=p;
            p=q;
        }
        return res;
    }
};
方法二,递归调用

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        <span style="color:#006600;">//reversed recursively</span>
        if(head==NULL||head->next==NULL){
            return head;
        }
        ListNode* p=head->next;
        ListNode* res=reverseList(p);
        head->next=NULL;
        p->next=head;
        return res;
    }
};



你可能感兴趣的:(22.leetcode题目206: Reverse Linked List)