您的位置:首页 > 其它

LeetCode 206. Reverse Linked List(翻转链表)

2016-05-04 08:22 337 查看
原题网址:https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

click to show more hints.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

方法一:迭代。

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


方法二:递归。
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode reversed;
private void reverse(ListNode prev, ListNode node) {
if (node == null) return;
reversed = node;
ListNode next = node.next;
node.next = prev;
reverse(node, next);
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
reverse(null, head);
return reversed;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: