zoukankan      html  css  js  c++  java
  • 35.翻转链表

    /**
     * Definition of singly-linked-list:
     *
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *        this->val = val;
     *        this->next = NULL;
     *     }
     * }
     */
    
    ///递归方法
    class Solution {
    public:
        /**
         * @param head: n
         * @return: The new head of reversed linked list.
         */
        ListNode * reverse(ListNode * head) {
            // write your code here
            if(head == NULL || head->next == NULL) return head;//先将头节点与最后一个节点翻转
            
            ListNode* r = reverse(head->next);
            head->next->next = head;//头节点以外的节点所以是把next的和next.next的翻转
            head->next = NULL;//头节点被转到最后一位 下一个为null
            
            return r;
    
        }
    };
    
    ///循环方法
    class Solution {
    public:
        /**
         * @param head: n
         * @return: The new head of reversed linked list.
         */
        ListNode * reverse(ListNode * head) {
            if (head == NULL) {
                return NULL;
            }
            ListNode *per = NULL, *cur = head, *net = head->next;
            while (net != NULL) {
                cur->next = per;
                per = cur;
                cur = net;
                net = cur->next;
            }
            cur->next = per;
            return cur;
        }
    };
    
  • 相关阅读:
    tensorflow 学习
    join-semi and join-anti
    深入拆解Tomcat_Jetty 笔记
    Set化
    DDD实战-笔记
    高并发系统设计-笔记
    技术管理
    性能调优-笔记
    程序员是如何思考的-笔记
    LeetCode
  • 原文地址:https://www.cnblogs.com/narjaja/p/9646155.html
Copyright © 2011-2022 走看看