【leetcode 24】 两两交换链表中的节点

37 阅读1分钟
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
import { ListNode } from "../../class";
const l4 = new ListNode(4);
const l3 = new ListNode(3, l4);
const l2 = new ListNode(2, l3);
const l = new ListNode(1, l2);

function swapPairs(head: ListNode | null): ListNode | null {
  if (head === null) return null;
  if (head.next === null) return head;
  //左位指针
  let left = head;
  while (left && left.next) {
    //保存右位的值
    const rightV = left.next.val;

    //交换两个位置的值
    left.next.val = left.val;
    left.val = rightV;

    // 指针向后移动两位
    left = left.next.next;
  }
  return head;
}
console.log(swapPairs(l));