代码随想录跟刷Day4


LeetCode24.链表两两交换

通过一个pre节点与cur节点实现节点指向的交换,用直观的逻辑去做

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        while(cur && cur->next){
            pre->next = cur->next;
            cur->next = cur->next->next;
            pre->next->next = cur;
            pre = cur;
            cur = pre->next;
        }
        return dummy->next;
    }
};

LeetCode19.删除链表倒数第n个节点

注意要建立一个哨兵节点,然后stack入栈方法是push,stack每个字母都是小写。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        stack<ListNode*> s;
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* cur = dummy;
        while(cur){
            s.push(cur);
            cur = cur->next;
        }
        for(int i = 0; i < n - 1; i++){
            s.pop();
        }
        ListNode* to_delete = s.top();
        s.pop();
        ListNode* pre = s.top();
        pre->next = to_delete->next;
        to_delete->next = nullptr;
        return dummy->next;
    }
};

LeetCode160.相交链表

算法就是从ListA的头遍历到ListB的头 与ListB的头遍历到ListA的头的指针比较地址是否相同。

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* cur1 = headA, *cur2 = headB;
        int reverse1 = 0, reverse2 = 0;
        while(cur1 && cur2){
            if(cur1 == cur2)
                return cur1;
            else
            {
                cur1 = cur1->next;
                cur2 = cur2->next;
                if(cur1 == nullptr && !reverse1){
                    cur1 = headB;
                    reverse1 = 1;
                }
                if(cur2 == nullptr && !reverse2){
                    cur2 = headA;
                    reverse2 = 1;
                }
            }
        }
        return nullptr;
    }
};

LeetCode142.环形链表

用unordered_set监测是否之前加入过该节点

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> s;
        ListNode* cur = head;
        while(cur){
            if(s.count(cur))
                return cur;
            else
                s.insert(cur);
            cur = cur->next;
        }
        return nullptr;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值