[24] 两两交换链表中的节点

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
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 || !head.next) {
    return head
  }
  var dummy = new ListNode()
  dummy.next = head
  var cur = dummy
  var ed = cur.next
  while (ed != null && ed.next != null) {
    var n1 = ed
    var n2 = ed.next
    cur.next = n2
    n1.next = n2.next
    n2.next = n1
    cur = n1
    ed = cur.next
  }
  return dummy.next;
};

 

posted @ 2023-11-30 13:38  人恒过  阅读(16)  评论(0)    收藏  举报