您的位置:首页 > 编程语言 > Java开发

Java [Leetcode 206]Reverse Linked List

2015-12-28 13:24 501 查看
题目描述:

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


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: