首页 > 编程语言 > 详细

Java [Leetcode 206]Reverse Linked List

时间:2015-12-28 14:11:36      阅读:263      评论:0      收藏:0      [点我收藏+]

题目描述:

Reverse a singly linked list.

解题思路:

使用递归或者迭代的方法。

代码如下:

方法一:递归

/**
 * 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) { //recursively
        return reverseListRecursive(head, null);
    }
    public ListNode reverseListRecursive(ListNode head, ListNode nextNode){
    	if(head == null)
    		return nextNode;
    	ListNode next = head.next;
    	head.next = nextNode;
    	return reverseListRecursive(next, head);
    }
}

方法二:迭代

public ListNode reverseList(ListNode head) { // iteratively
    	ListNode nextNode = null;
    	while(head != null){
    		ListNode next = head.next;
    		head.next = nextNode;
    		nextNode = head;
    		head = next;
    	}
    	return nextNode;
    }

  

 

Java [Leetcode 206]Reverse Linked List

原文:http://www.cnblogs.com/zihaowang/p/5082242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!