• 206 Reverse Linked List 反转链表


    反转一个单链表。
    进阶:
    链表可以迭代或递归地反转。你能否两个都实现一遍?
    详见:https://leetcode.com/problems/reverse-linked-list/description/

    Java实现:

    迭代实现:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null){
                return null;
            }
            ListNode cur=head;
            ListNode pre=null;
            ListNode next=null;
            while(cur!=null){
                next=cur.next;
                cur.next=pre;
                pre=cur;
                cur=next;
            }
            return pre;
        }
    }
    

    递归实现:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null||head.next==null){
                return head;
            }
            ListNode p=head;
            head=reverseList(p.next);
            p.next.next=p;
            p.next=null;
            return head;
        }
    }
    

     C++实现:

    方法一:非递归

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(head==nullptr)
            {
                return nullptr;
            }
            ListNode *cur=head;
            ListNode *pre=nullptr;
            ListNode *next=nullptr;
            while(cur)
            {
                next=cur->next;
                cur->next=pre;
                pre=cur;
                cur=next;
            }
            return pre;
        }
    };
    

     方法二:递归

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(head==nullptr||head->next==nullptr)
            {
                return head;
            }
            ListNode *p=head;
            head=reverseList(p->next);
            p->next->next=p;
            p->next=nullptr;
            return head;
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/4478820.html

  • 相关阅读:
    动态模板列更新数据分页的例子
    Oracle SCN机制解析
    阻止特定的ip登陆数据库的2种方法 (轉)
    Oracle动态执行SQL四种方式的例子
    使用Oracle的DBMS_SQL包执行动态SQL语句
    Oracle XML DB之浅入浅出
    将oracle设为归档模式和非归档模式启动的方法
    如何修改Oracle數據庫字符集
    (原創)C#使用QueryTables導出到Excel
    常用SQL語句2
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8746530.html
Copyright © 2020-2023  润新知