当前位置:网站首页>1721. exchange nodes in the linked list

1721. exchange nodes in the linked list

2022-06-11 08:55:00 Drag is me

leetcode Force button to brush questions and punch in

subject :1721. Exchange the nodes in the linked list
describe : Give you the head node of the list head And an integer k .

In exchange for Positive number of linked list k Nodes and penultimate k After the value of a node , Return the head node of the linked list ( Linked list from 1 Start index ).

Their thinking

1、 Use an array to store linked list nodes , Locate two target nodes with subscripts , Then exchange ;
2、 Double pointer is OK , See the code 2.

Source code 1##

class Solution {
    
public:
    ListNode* swapNodes(ListNode* head, int k) {
    
        vector<ListNode *>v;
        ListNode *p = new ListNode(-1);
        ListNode *pp = p;
        int n = 0;
        while (head) {
    
            v.emplace_back(head);
            head = head->next;
        }
        n = v.size();
        int val = v[k - 1]->val;
        v[k - 1]->val = v[n - k]->val;
        v[n - k]->val = val;
        for (int i = 0; i < n; ++i) {
    
            p->next = v[i];
            p = p->next;
        }
        p->next = nullptr;
        return pp->next;
    }
};

Source code 2##

class Solution {
    
public:
    ListNode* swapNodes(ListNode* head, int k) {
    
        ListNode *fast = head;
        for (int i = 1; i < k; ++i) {
    
            fast = fast->next;
        }
        ListNode *temp = fast;
        ListNode *slow = head;
        while (fast->next != nullptr) {
    
            fast = fast->next;
            slow = slow->next;
        }
        swap(slow->val, temp->val);
        return head;
    }
};
原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855011788.html