240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 2 | Leetcode 206. Reverse Linked List

题解

逆序链表,基本功之一。

用递归写起来很简单,但需要消耗大量栈空间,更推荐使用迭代的方法。通过画图找到变换关系。

// Original Linked List:
? --> p --> q --> r --> ?

// Assume the elements before p have been reversed like in step 0),

0) ? <-- p     q --> r --> ?

// then at this step, we do the reverse,

1) ? <-- p <-- q     r --> ?

// and move to the next step.

2) ? <-- ? <-- p     q --> r --> ?

迭代方法如下:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head) return head;
        
        ListNode* prehead = new ListNode(0);
        prehead->next = head;

        ListNode *p = prehead, *q = head;

        while(p && q) {
            // reverse
            ListNode* r = q->next;
            q->next = p;

            // move
            p = q;
            q = r;
        }

        head->next = nullptr;
        head = p;

        return head;  
    }
};
posted @ 2020-07-04 06:57  CasperWin  阅读(89)  评论(0编辑  收藏  举报