美文网首页
[刷题防痴呆] 0024 - 两两交换链表中的节点 (Swap

[刷题防痴呆] 0024 - 两两交换链表中的节点 (Swap

作者: 西出玉门东望长安 | 来源:发表于2021-12-10 01:30 被阅读0次

题目地址

https://leetcode.com/problems/swap-nodes-in-pairs/description/

题目描述

24. Swap Nodes in Pairs


Given a linked list, swap every two adjacent nodes and return its head.

 

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]

思路

  • dummy的运用.
  • 每次往后走两步.
  • 相互交换. head.next = n2. n1.next = n2.next. n2.next = n1.
  • 交换后, head往后走一步. head = n1.

关键点

代码

  • 语言支持:Java
/**
 * 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; }
 * }
 */
/**
 * 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) {
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;

        while (cur.next != null && cur.next.next != null) {
            ListNode n1 = cur.next;
            ListNode n2 = cur.next.next;

            cur.next = n2;
            n1.next = n2.next;
            n2.next = n1;

            cur = cur.next.next;
        }
        
        return dummy.next;
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0024 - 两两交换链表中的节点 (Swap

      本文链接:https://www.haomeiwen.com/subject/qmmzxrtx.html