这个题我在Hedvig电面的时候是热身题。。iteration and recursion。
recursion的时候我用了个global指针。。对方说不需要的时候,我直接懵逼了,当时脑子一片空白。。
这次做又卡了一下,好奇怪,已经有心理阴影了,这他妈是EAZY难度的啊。。。。
其实可以参考 post order的意思,一开始没有想到的一个概念是回来之后,还可以通过head.next来指代下一个NODE。。
head.next.next = head; 我真是傻逼。。这个题还像模像样的分析。。
Recursion:
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode temp = reverseList(head.next);
head.next.next = head;
head.next = null;
return temp;
}
}
Iteration:
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null;
ListNode temp = head;
ListNode next = head.next;
while (next != null) {
temp.next = prev;
prev = temp;
temp = next;
next = next.next;
}
temp.next = prev;
return temp;
}
}
= = 这个题都写笔记,让我很有挫败感。