数据结构与算法每日一题——链表(24. 两两交换链表中的节点)

36 阅读1分钟

24. 两两交换链表中的节点

image.png

/**
 * 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) {
    let dummyHead = new ListNode(0,head)
    let cur = dummyHead
    while(cur.next && cur.next.next){
        let temp =cur.next
        let temp1 = cur.next.next.next
        cur.next = cur.next.next
        cur.next.next = temp
        temp.next = temp1
        cur = cur.next.next
    }
    return dummyHead.next
};