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;
        }
    }
  • 相关阅读:
    Java--数组转成list,list转数组
    js禁用后退
    正则
    实用符号Alt+小键盘快输
    Minimum Depth of Binary Tree
    Balanced Binary Tree
    Valid Palindrome [leetcode]
    Sum Root to Leaf Numbers
    reorder List
    判断链表 有环
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12114566.html
Copyright © 2011-2022 走看看