五月集训(第12天)— 链表

链表

1. 1290. 二进制链表转整数

    思路:
        遍历链表,将二进制数转化未十进制数。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        int sum = 0;
        while (head != NULL) {
            sum = sum * 2 + head->val;
            head = head->next;
        }
        return sum;
    }
};

2. 237. 删除链表中的节点

    思路:
        想要删除一个结点似乎是必须要知道他的前驱结点才行。但是实际上换个想法,直接把要删除的结点变成它的后继结点,然后再删除其后继结点即可。妙啊!

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

3. 剑指 Offer II 024. 反转链表

    思路:
        定义一个新的表头指针new_head用来生成反转链表。具体操作为:
            1. 将当前结点的前驱指向其后继结点(删除当前结点)
            2. 将被删除的结点指向新链表的表尾
        中间操作是每次将new_head指向表尾,下一个结点指向new_head即可。
        

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL) return head;
        ListNode *pre = head;
        ListNode *cur = head->next;
        ListNode *new_head = head;
        while (cur) {
            pre->next = cur->next;  /* 从原链表中删除当前结点,将其指向新链表 */
            cur->next = new_head;
            new_head = cur;
            cur = pre->next;
        }
        return new_head;
    }
};

4. 1019. 链表中的下一个更大节点

    思路:
        维护一个单调栈,找出每一个大于nums[i]的数。

单调栈模板


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
#define maxn 10005
public:
    vector<int> nextLargerNodes(ListNode* head) {
        stack<int> stk;
        vector<int> ret;
        int n = 0, temp;
        while (head) {
            ret.push_back(head->val);
            head = head->next;
            n++;
        }
        for (int i = n - 1; i >= 0; i--) {
            while (!stk.empty() && stk.top() <= ret[i]) {
                stk.pop();
            }
            temp = ret[i];
            ret[i] = ( stk.empty() ? 0 : stk.top() );
            stk.push(temp);
        }
        return ret;
    }
};
posted @ 2022-05-14 07:41  番茄元  阅读(7)  评论(0)    收藏  举报