【LeetCode】24. Swap Nodes in Pairs

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

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题意:给定一个链表,将其每两个元素进行对调。

思路:案例没讲清楚,实际上如果一组不足两个元素,则不操作,比如1->2->5,操作后应变为2->1->5。分析起来不麻烦,注意边界就好

代码如下:

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        
        
        ListNode now = head, pre = null, next, newhead = head.next;
        
        while (now != null && now.next != null){
            next = now.next;
            now.next = next.next;
            next.next = now;
            
            if (pre != null){
                pre.next = next;
            }
            
            pre = now;
            now = now.next;
        }
        
        return newhead;
    }
点赞