码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 206. Reverse Linked List

时间:2019-12-29 12:44:23      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:code   def   bsp   ||   ret   The   nod   efi   amp   

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;
    }
}

[LC] 206. Reverse Linked List

标签:code   def   bsp   ||   ret   The   nod   efi   amp   

原文地址:https://www.cnblogs.com/xuanlu/p/12114566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!