zoukankan      html  css  js  c++  java
  • [LC] 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?

    Iterative:

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

    Recursive:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode nxt = head.next;
            ListNode newHead = reverseList(nxt);
            nxt.next = head;
            head.next = null;
            return newHead;
        }
    }
  • 相关阅读:
    《道德经》全文
    mysql 服务启动后停止
    安装docker-compose
    金刚般若波罗蜜经
    elasticsearch reIndex
    【基础篇】1.vim复制黏贴跳转
    新事物如何持续性发展
    舒服的状态
    教父
    关于拖延
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12114566.html
Copyright © 2011-2022 走看看