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

Reverse Linked List

时间:2016-08-13 10:01:36      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Reverse a singly linked list.

recursive version

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

  iterative version

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

        ListNode tail = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = tail;
            tail = head;
            head = temp;
        }
        return tail;
    }
}

  

Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5767235.html

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