0
点赞
收藏
分享

微信扫一扫

IDEA创建一个web项目部署到tomcat

一只1994 2024-01-28 阅读 10

复杂度

时间复杂度: O ( n ) O(n) O(n)

空间复杂度: O ( 1 ) O(1) O(1)

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
	public ListNode swapPairs(ListNode head)
	{
		if (head == null)
			return head;
		ListNode pre = new ListNode(0, head);//前驱节点 执行 first
		ListNode ans = pre;
		ListNode first = pre.next;// 第一个节点

		while (first.next != null)
		{
			ListNode second = first.next;// 第二个节点
			ListNode tail = second.next;// 后续节点
			//交换第一、二个节点
			pre.next = second;
			second.next = first;
			//把后续的节点接到交换后的 first 节点上
			first.next = tail;
			pre = first;// pre 为交换后靠后的 first节点
            first = pre.next;//first = pre.next;
			if (tail == null)//后续无节点了直接结束
				break;
		}
		return ans.next;
	}
}
举报

相关推荐

0 条评论