|
| 1 | +# 1721. Swapping Nodes in a Linked List |
| 2 | + |
| 3 | +- Difficulty: Medium. |
| 4 | +- Related Topics: Linked List, Two Pointers. |
| 5 | +- Similar Questions: Remove Nth Node From End of List, Swap Nodes in Pairs, Reverse Nodes in k-Group. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +You are given the `head` of a linked list, and an integer `k`. |
| 10 | + |
| 11 | +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**).** |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +``` |
| 19 | +Input: head = [1,2,3,4,5], k = 2 |
| 20 | +Output: [1,4,3,2,5] |
| 21 | +``` |
| 22 | + |
| 23 | +Example 2: |
| 24 | + |
| 25 | +``` |
| 26 | +Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 |
| 27 | +Output: [7,9,6,6,8,7,3,0,9,5] |
| 28 | +``` |
| 29 | + |
| 30 | + |
| 31 | +**Constraints:** |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +- The number of nodes in the list is `n`. |
| 36 | + |
| 37 | +- `1 <= k <= n <= 105` |
| 38 | + |
| 39 | +- `0 <= Node.val <= 100` |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +## Solution |
| 44 | + |
| 45 | +```javascript |
| 46 | +/** |
| 47 | + * Definition for singly-linked list. |
| 48 | + * function ListNode(val, next) { |
| 49 | + * this.val = (val===undefined ? 0 : val) |
| 50 | + * this.next = (next===undefined ? null : next) |
| 51 | + * } |
| 52 | + */ |
| 53 | +/** |
| 54 | + * @param {ListNode} head |
| 55 | + * @param {number} k |
| 56 | + * @return {ListNode} |
| 57 | + */ |
| 58 | +var swapNodes = function(head, k) { |
| 59 | + if (!head) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + let left = head, right = head; |
| 63 | + for (let i = 1; i < k; i++) { |
| 64 | + left = left.next; |
| 65 | + } |
| 66 | + let curr = left; |
| 67 | + while (curr.next) { |
| 68 | + curr = curr.next; |
| 69 | + right = right.next; |
| 70 | + } |
| 71 | + let temp = left.val; |
| 72 | + left.val = right.val; |
| 73 | + right.val = temp; |
| 74 | + return head; |
| 75 | +}; |
| 76 | +``` |
| 77 | + |
| 78 | +**Explain:** |
| 79 | + |
| 80 | +nope. |
| 81 | + |
| 82 | +**Complexity:** |
| 83 | + |
| 84 | +* Time complexity : O(n). |
| 85 | +* Space complexity : O(1). |
0 commit comments