1721. Swapping Nodes in a Linked List

题目:

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

Example 3:

Input: head = [1], k = 1
Output: [1]

Example 4:

Input: head = [1,2], k = 1
Output: [2,1]

Example 5:

Input: head = [1,2,3], k = 2
Output: [1,2,3]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 10^5
  • 0 <= Node.val <= 100

思路:

题目大意是给定一个list和一个数k,swap第k个和倒数第k个。因为数据量不大,多种方法可以做:用额外空间存下来然后置换;走两遍,第一次记录第k个和总node数,第二次找到倒数第k个即可。虽然复杂度都是O(n),但是面试肯定会要求one pass无额外空间。总体来说我们需要两个node作为iterator去遍历,首先走k步,我们找到了第k个,这就是第一个要swap的node;然后我们知道了当前node到原head的距离是k,这时候用另一个node从head开始,保持两个iterator node同步走,那么当前面的那个iterator走到结尾时,后面的那个距离结尾正好是k个(即倒数第k个),和之前记录的Node交换即可。本题因为只检查val,不用真实地交换node,直接交换val即可。

代码:

/**
 * 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* swapNodes(ListNode* head, int k) {
        ListNode* temp=head;
        for(int i=0;i<k-1;i++)
            temp=temp->next;
        ListNode* sec=head;
        ListNode* fir=temp;
        while(temp->next)
        {
            temp=temp->next;
            sec=sec->next;
        }
        swap(fir->val,sec->val);
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_49991368/article/details/112460608