题目:206. 反转链表
法1:模拟
class Solution {
public ListNode reverseList(ListNode head) {
ListNode curr = null;
ListNode prev = head;
while (prev != null) {
ListNode t = prev.next;
prev.next = curr;
curr = prev;
prev = t;
}
return curr;
}
}
法2:递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode ans = reverseList(head.next);
head.next.next = head;
head.next = null;
return ans;
}
}
法3:妖魔化的双指针
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode curr = head;
while (head.next != null) {
ListNode t = head.next.next;
head.next.next = curr;
curr = head.next;
head.next = t;
}
return curr;
}
}
总结:
/**
* 总结:
* 1.真的能深刻的感受到不刷题我的编程思维就不会提升。自己写的代码的太垃圾了。
* 2.善于总结和复习,不然写过的题又忘记,没有意义。
*/