解法一:迭代
一共有三个指针,preNode,head,recordNext,三个指针会慢慢迭代向后面的节点
java描述:
public ListNode reverseList(ListNode head) {
ListNode preNode = null;
while (head != null) {
ListNode recordNext = head.next;
head.next = preNode;
preNode = head;
head = recordNext;
}
return preNode;
}
javaScript描述:
var reverseList = function(head) {
let preNode = null;
while (head != null) {
let recodeNode = head.next;
head.next = preNode;
preNode = head;
head = recodeNode;
}
return preNode;
};
解法二:递归
也是一共有三个指针,head,preNode,next,关键有两点,一是head.next要先赋值,不然后面值会丢。
二是通过 return reverseListInt(next, head);来移动指针。
java描述:
public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
}
public ListNode reverseListInt(ListNode head, ListNode preNode) {
if (head == null) {
return preNode;
}
ListNode next = head.next;
head.next = preNode;
return reverseListInt(next, head);
}
javaScript描述:
var reverseList = function(head) {
return reverseListInt(head, null);
};
function reverseListInt(head, preNode) {
if(!head) {
return preNode;
}
let next = head.next;
head.next = preNode;
return reverseListInt(next, head);
}