【LeetCode】#24两两交换链表中的节点(Swap Nodes in Pairs)

【LeetCode】#24两两交换链表中的节点(Swap Nodes in Pairs)

题目描述

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

示例

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

Description

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

Example

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

解法

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode l1 = head;
        ListNode l2 = head.next;
        ListNode l3 = l2.next;
        ListNode l4 = l2.next;
        if(l3!=null){
            l4 = l3.next;
        }
        if(l1==null || l2==null){
            return head;
        }
        head = l2;
        while(l1!=null && l2!=null){
            l2.next = l1;
            if(l4!=null){
                l1.next = l4;
            }else{
                l1.next = l3;
                break;
            }
            l1 = l3;
            l2 = l4;
            if(l4==null){
                l3 = null;
            }else{
                l3 = l4.next;
            }
            if(l3==null){
                l4 = null;
            }else{
                l4 = l3.next;
            }
        }
        
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84747526