zoukankan      html  css  js  c++  java
  • 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;  
        }
    };
    
  • 相关阅读:
    sql
    Java 反射
    Java 泛型
    Java 数组小记
    Java 实现二叉树
    Maven的环境配置
    用于解决easui 保存时候,前台传参是空字符串不null
    SpringMVC
    SpringMVC
    解决MySql varchar类型的数字排序
  • 原文地址:https://www.cnblogs.com/casperwin/p/13233630.html
Copyright © 2011-2022 走看看