LeetCode

Editorial: LeetCode 1721 Swapping Nodes in a Linked List

Editorial: LeetCode 1721 Swapping Nodes in a Linked List

https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ from Amazon

Thinking process:

Simple question. Just find the length of the linked list first, and then do the operation.

Here is the code.

 1class Solution {
 2public:
 3    int len(ListNode* head) {
 4        int r = 0;
 5        while (head) {
 6            r++;
 7            head = head->next;
 8        }
 9        return r;
10    }
11    ListNode* swapNodes(ListNode* head, int k) {
12        int L = len(head);
13        ListNode* n1;
14        ListNode* n2;
15        ListNode* cur = head;
16        for (int i=0; i<=max(L-k, k-1); i++) {
17            if (i == k-1) n1 = cur;
18            if (i == L-k) n2 = cur;
19            cur = cur->next;
20        }
21        int tmp = n1->val;
22        n1->val = n2->val;
23        n2->val = tmp;
24        return head;
25    }
26};
comments powered by Disqus