LeetCode 随机 - 两两交换链表中的节点

版权声明:本文出自 whdAlive 的博客,转载必须注明出处 https://blog.csdn.net/whdAlive/article/details/89028815

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

代码

/**
 * 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 || head.next == null) {
            return head;
        }
        ListNode st = new ListNode(-1);
        st.next = head;
        
        //维护三个节点,前驱、当前和后继节点
        //当前节点始终为奇数个节点,与后继节点组成需要交换的节点对
        ListNode left = st, mid = head, right = head.next;
        //当前节点非空,后继节点非空 -- 当前需要交换
        while(mid != null && mid.next != null) {
            //交换三个节点的指向关系
            mid.next = right.next;
            right.next = mid;
            left.next = right;
            
            //遍历后续节点
            left = mid;
            mid = left.next;
            
            //判断是否存在后续节点
            if(mid != null && mid.next != null) {
                right = mid.next;
            }
        }
        return st.next;
    }
}

猜你喜欢

转载自blog.csdn.net/whdAlive/article/details/89028815