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

206. Reverse Linked List

时间:2019-02-01 14:11:00      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:tno   span   efi   inpu   style   color   一个   node   lis   

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 = null;
        while(head != null){
            ListNode next = head.next;
            head.next = cur;
            cur = head;
            head = next;
        }
        return cur;
    }
}

递归,每次减小一个

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

 

206. Reverse Linked List

标签:tno   span   efi   inpu   style   color   一个   node   lis   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10345468.html

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