zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    28完全背包+扩展欧几里得(包子凑数)
    HDU 3527 SPY
    POJ 3615 Cow Hurdles
    POJ 3620 Avoid The Lakes
    POJ 3036 Honeycomb Walk
    HDU 2352 Verdis Quo
    HDU 2368 Alfredo's Pizza Restaurant
    HDU 2700 Parity
    HDU 3763 CDs
    POJ 3279 Fliptile
  • 原文地址:https://www.cnblogs.com/parzulpan/p/10061488.html
Copyright © 2011-2022 走看看