Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Explanation:
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
Constraints:
The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100
문제 풀이
노드의 연결관계를 다시 세팅하기위해 특정 노드의 prev, next의 값을 유지하는게 중요
3번의 1~4번을 next가 null인 경우, 즉 비교할 대상이 없을 때 까지 반복하여 진행
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
if (!head) return head;
let dummy = new ListNode(0, head);
let prev = dummy;
let current = head;
while (current && current.next) {
const node1 = current;
const node2 = current.next;
const node3 = node2.next;
prev.next = node2;
node2.next = node1;
node1.next = node3;
prev = node1;
current = node1.next;
}
return dummy.next;
};
결론
연결 관계에서 swap을 잘 하기 위해 prev, next의 연결 정보를 유지시켜 두는게 핵심