0
点赞
收藏
分享

微信扫一扫

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

九点韶留学 2022-06-27 阅读 56

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

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;
}
}


举报

相关推荐

0 条评论