码迷,mamicode.com
首页 > 编程语言 > 详细

Java [Leetcode 206]Reverse Linked List

时间:2015-12-28 14:12:02      阅读:214      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!