• LeetCode206 反转链表


    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

     


     

     

    //章节 - 链表    
    //三、经典问题
    //1.反转链表
    /*
    算法思想:
        递归方法,
    */
    //算法实现:
    /**
     * 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 == NULL || head->next == NULL)
                return head;
            ListNode *newhead = reverseList(head->next);
            head->next->next = head;
            head->next = NULL;
            return newhead;
        }
    };
    */
    /*
    算法思想:
        迭代方法,
    */
    //算法实现:
    class Solution {
    public:
        ListNode* reverseList(ListNode *head) {
            ListNode *newhead = NULL;
            ListNode *now;
            while (head != NULL) {
                now = head;         //取头
                head = head->next;   //更新原链头
                now->next = newhead; //插入新链
                newhead = now;      //更新新链头
            }
            return newhead;
        }
    };
  • 相关阅读:
    开启linux服务器防火墙
    Linux系统编程11_管道和命名管道
    Lua语法
    Git学习
    Buildroot介绍
    Makefile基本介绍
    页、页表和块
    文件系统,根文件系统,MTD
    什么是ioctl
    bootargs的mtdparts解析
  • 原文地址:https://www.cnblogs.com/parzulpan/p/10061488.html
Copyright © 2020-2023  润新知