原题网址:https://leetcode.com/problems/reverse-linked-list/
Reverse a singly linked list.
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;
}
}