zoukankan      html  css  js  c++  java
  • LeetCode 206. Reverse Linked List(C++)

    题目:

    Reverse a singly linked list.

    Example:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL
    

    Follow up:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    分析:

    分别用迭代和递归来实现。

    迭代就是新建一个newhead节点,遍历原链表,将每一个node接到newhead,注意保存head->next用来更新head。

    递归则是利用函数先走到链表尾端,依次更新每一个node的next,最后返回newhead。

    程序:

    //iteratively
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode *newhead = NULL;
            while(head){
                ListNode *p = head->next;
                head->next = newhead;
                newhead = head;
                head = p;
            }
            return newhead;
        }
    };
    //recursively
    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;
        }
    };
  • 相关阅读:
    微信小程序
    svn
    当滑动条滑动到某一位置触发js
    css固定页面
    css三级菜单
    h5时钟
    DOM节点
    应用r.js来优化你的前端
    浅谈javascript中的作用域
    javascript 中的 arguments,callee.caller,apply,call 区别
  • 原文地址:https://www.cnblogs.com/silentteller/p/10459455.html
Copyright © 2011-2022 走看看