参考链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/
- 自己的解法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode headTemp = head;
ListNode result = new ListNode(0);
ArrayList<ListNode> num =new ArrayList<ListNode>();
int len = 0;
while(headTemp != null){
++len;
num.add(headTemp);
headTemp = headTemp.next;
}
result.next = num.get(len - 1);
for(int i = len - 1;i>=0;i--){
if(i == 0){
num.get(i).next = null;
}
else{
num.get(i).next = num.get(i - 1);
}
}
return result.next;
}
}
- 迭代解法
解法的难点在于对于任一对节点,当我将第二个节点的指针指向第一个节点时,则无法抵达第三节点,此时设立一个temp保存第三指针,类似早年的数据排序。
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
- 递归解法
递归解法的三个条件:大问题拆成两个子问题;子问题求解方式和大问题一样;存在最小子问题。
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}