LeetCode024——两两交换链表中的节点

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82377317

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/

题目描述:

知识点:链表

思路:三指针遍历链表

如果题目没有要求使用常数的额外空间,我们完全可以用一个数组来存储链表中每一节点的值,再按照数组中的值新建一个链表。

链表相关的题,多设指针,在草稿纸上多演练几次,一定能够轻松解决。

为了避免对头节点的特殊处理,我们设立虚拟头节点dummyHead。

设立三个指针cur1、cur2和cur3,cur1指向待交换的第一个节点的前一个节点,cur2指向待交换的第一个节点,cur3指向待交换的第二个节点。在给cur2和cur3节点赋值之前,我们都要判断能否赋值,即cur1.next和cur1.next.next是否为null。如果为null,我们直接返回dummyHead.next。否则,我们进行交换操作。值得注意的是,交换完之后我们的顺序会变成cur1 -> cur3 -> cur2,因此我们新的cur1应该指向cur2

我们只遍历了一次链表,因此时间复杂度是O(n),其中n为链表中总节点数。整个过程只涉及cur1、cur2和cur3这三个指针的操作,因此空间复杂度是O(1)。

JAVA代码:

public class Solution {
	
	public ListNode swapPairs(ListNode head) {
		ListNode dummyHead = new ListNode(-1);
		dummyHead.next = head;
		ListNode cur1 = dummyHead;
		if(cur1.next == null || cur1.next.next == null) {
			return dummyHead.next;
		}
		ListNode cur2 = cur1.next;
		ListNode cur3 = cur2.next;
		while(true) {
			cur2.next = cur3.next;
			cur1.next = cur3;
			cur3.next = cur2;
			cur1 = cur2;
			if(cur1.next == null || cur1.next.next == null) {
				return dummyHead.next;
			}
			cur2 = cur1.next;
			cur3 = cur2.next;
		}
	}
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82377317