迭代法
思想:一边是新链表,一边是原链表。不断地将原链表的头节点头插到新链表中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode list = head;
ListNode newList = null;
ListNode current = null;
while (list != null) {
//保存下一个节点
current = list.next;
//处理当前头节点,将其头插到新链表
list.next = newList;
newList = list;
list = current;
}
return newList;
}
}
递归法
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode sublist = reverseList(head.next);
if (sublist == null)
return head;
ListNode current = sublist;
while (current.next != null) {
current = current.next;
}
head.next = current.next;
current.next = head;
return sublist;
}
}
看到更简单的递归
public ListNode reverseList(ListNode head) {
/* recursive solution */
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
//保存下一个要处理的结点
ListNode next = head.next;
//在原链表处理头结点
head.next = newHead;
//处理下一个结点
return reverseListInt(next, head);
}
感觉迭代的方法更容易实现。