24. Swap Nodes in Pairs【两两交换链表中的节点】

在这里插入图片描述

package LeetCode;

public class Test {
	public static void main(String[] args) {
		
		ListNode l1 = new ListNode(1);
		ListNode l2 = new ListNode(2);
		ListNode l3 = new ListNode(3);
		ListNode l4 = new ListNode(4);
		ListNode l5 = new ListNode(5);
		l1.next = l2;
		l2.next = l3;
		l3.next = l4;
		l4.next = l5;
		
		ListNode test = l1;
		while (test != null) {
			System.out.print(test.val + "\t");
			test = test.next;
		}
		
		System.out.println();
		
		ListNode res = swapPairs(l1);
		
		while (res != null) {
			System.out.print(res.val + "\t");
			res = res.next;
		}
	}
	
	/**
	 * 参考:https://leetcode.com/problems/swap-nodes-in-pairs/discuss/345819/Java-Solution-beats-100-on-both.-Solely-ListNode-operations.
	 * 1. 如果列表为空,则返回空列表。
	 * 2. 如果列表只有1个元素,则返回列表本身。
	 * 3. 如果列表元素大于等于2个
	 * 3.1 调换第1个和第2个节点,头节点为第2个节点
	 * 3.2 从第3个节点开始,利用循环开始调换
	 */
    public static ListNode swapPairs(ListNode head) {
    	//1. 如果列表为空,则返回空列表。
    	//2. 如果列表只有1个元素,则返回列表本身。
    	if(head == null || head.next == null) {
    		return head;
    	}
    	
    	//3.1 调换第1个和第2个节点,头节点为第2个节点
    	ListNode temp = head.next;
    	head.next = head.next.next;
    	temp.next = head;
    	head = temp;
    	
    	//3.2 从第3个节点开始,利用循环开始调换
    	ListNode ans = head;
    	ListNode curr = head.next;
    	
    	while (curr != null && curr.next != null && curr.next.next != null) {
    		ListNode temp1 = curr.next;
    		ListNode temp2 = curr.next.next;
    		
    		curr.next = temp2;
    		temp1.next = temp2.next;
    		temp2.next = temp1;
    		curr = temp1;
    	}
    	
    	return ans;
    }
}

发布了63 篇原创文章 · 获赞 1 · 访问量 2759

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/97790569