【算法】【线性表】【链表】Swap Nodes in Pairs 两两交换链表中的节点

1  题目

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]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

2  解答

这个就比较得心应手了,加个头节点:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        // 参数边界校验
        if (head == null || head.next == null) {
            return head;
        }
        // 来个头节点 方便处理
        ListNode preNode = new ListNode(0);
        preNode.next = head;
        
        // node永远指向两个节点的前一个节点
        ListNode node = preNode;
        while (node != null) {
            // 第一个节点
            ListNode nextOneNode = node.next;
            if (Objects.isNull(nextOneNode)) break;
            // 第二个节点
            ListNode nextTwoNode = nextOneNode.next;
            if (Objects.isNull(nextTwoNode)) break;
            
            // 交换两个节点
            // 第二个节点的尾部给到第一个节点的next
            nextOneNode.next = nextTwoNode.next;
            nextTwoNode.next = nextOneNode;
            node.next = nextTwoNode;
            node = nextOneNode;
        }
        return preNode.next;
    }
}

加油。

posted @ 2024-01-15 07:58  酷酷-  阅读(7)  评论(0编辑  收藏  举报