LeetCode笔记汇总
题目
思路
双指针迭代
迭代的思想是从左边开始两两交换链表中的节点。交换两个节点,使用一个长度为3的滑动窗口。窗口中的元素分别为pre,cur,temp。实际交换的是前两个节点,第三个temp节点主要用于存储,避免在改变cur.next后访问不到原链表中cur后面的元素。最开始时让pre指向null,从而达到将第一个节点的next置空的目的,否则将始终指向原链表的第二个元素。每次交换之后让三个指针后移一位即可,直至cur指针为空。
递归
代码
//迭代
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode tmp = null;
while(cur != null) {
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
//递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}