• 206. Reverse Linked List


    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?

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

    迭代,原理是设置一个prev和cur分别指向前一个和当前的指针,每次都是先要保存当前指的下一个防止丢失。然后每一步都只reverse一个,即cur指向prev,直到最后一个。

    递归,每次减小一个

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

    Recursively 的讲解:https://www.youtube.com/watch?time_continue=1&v=MRe3UsRadKw

  • 相关阅读:
    索引
    运算符优先级
    身份运算符
    成员运算符
    位运算符
    利用java编写物品的品牌、尺寸、价格、库存(新手)
    今天聊一聊nuxt.js(上)
    初入前端,面对一个项目应注意哪些?
    小型 Web 页项目打包优化方案
    跨域的那些事儿
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10345468.html
Copyright © 2020-2023  润新知