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

在这里插入图片描述


解题思路:
1 重点:如何在交换完了之后,获得进行交换动作的两个节点的前驱节点;思路和反转链表类似,维护一个前驱节点即可。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        
        if (head == null)
            return null;
        
        ListNode prepre = new ListNode(-1);
        prepre.next = head;
        
        ListNode pre = head;
        ListNode now = head.next;
        
        ListNode result = prepre;
        
        for (;now != null;){
        
            pre.next = now.next;
            now.next = pre;
            prepre.next = now;
        
            if (pre.next == null)
                break;
            
            prepre = pre;
            pre = pre.next;
            now = pre.next;
        }
        
        return result.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36269372/article/details/84780813