Leetcode brush question (single linked list) 8 - two-by-two exchange of nodes in the linked list

24. Exchange the nodes in the linked list two by two

Given a linked list, exchange the adjacent nodes in it two by two, and return the exchanged linked list.
You can't just change the value inside the node, but you need to actually swap the node.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    //执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
    //内存消耗:37.6 MB, 在所有 Java 提交中击败了16.60%的用户
    public ListNode swapPairs(ListNode head) {
    
    
        ListNode p = head;
        int flag = 0;
        //需要考虑到[1,2,3]这种最后不满足两个的不交换
        while(p != null && p.next != null){
    
    
             ListNode q = p.next;
             p.next = q.next;
             q.next = p;
             //第一组交换时,改变head
            if(flag == 0){
    
    
                flag = 1;
                head = q;
            }
            p = p.next;
              //需要考虑到[1,2,3]这种最后不满足两个的不交换
              //此处是将两两连接部分改变
            if(p != null && p.next != null)
                q.next.next = p.next;
        }
        return head;
    }
   
}

Guess you like

Origin blog.csdn.net/qq_38754625/article/details/108538589