代码随想录day3

76 阅读1分钟

203.移除链表元素

主要需掌握虚拟头结点的运用

707.设计链表

需要注意index从0开始,头结点为第0个结点

while(index--){ // 如果--index 就会陷入死循环   因为若是index = 0 --变为负数,死循环
            cur = cur->next;
        }
        return cur->val;

还需注意cur的指向,是指向虚拟结点还是头结点 and 题目的描述有一点问题

206.翻转链表

双指针法

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur) {
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

最后return的是pre 因为cur等于temp,返回cur的话结果为空。

递归法

class Solution {
public:
    ListNode* reverse(ListNode* pre,ListNode* cur){
        if(cur == NULL) return pre;
        ListNode* temp = cur->next;
        cur->next = pre;
        // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
        // pre = cur;
        // cur = temp;
        return reverse(cur,temp);
    }
    ListNode* reverseList(ListNode* head) {
        // 和双指针法初始化是一样的逻辑
        // ListNode* cur = head;
        // ListNode* pre = NULL;
        return reverse(NULL, head);
    }

};