https://leetcode.cn/problems/swap-nodes-in-pairs/?envType=study-plan-v2&envId=top-100-liked
对于我们正常交换单向链表的两个节点我们需要知道三个节点的信息, 1.对于a->b->c,我们要交换a、b就要知道a、b、c三个节点,因为我们需要将a的next指向c,将b的next指向a,由于b->c这条路断了而c的next指向d,所以我们还需要保存c才能继续往下走,我们将b看作curr它每次前进两步,a看作prev,c看作next,每次使curr.next = prev, prev.next = next,然后令prev = next, curr = next.next,next = curr.next当prev或curr有一个为空就退出. 2.若对于a->b->c->d,我们要交换c、d我们就需要知道四个节点信息,b,c,d,e=d.next,d.next = c, c.next = e, b.next = d, 我们将b视作prev,c视作curr1,d视作curr2,e视作next. 所以我们需要考虑两种情况,当交换的节点包括头节点就用方法一其余用方法二
public class Solution {
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; }
}
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null, curr1 = head, curr2 = head.next, next = curr2.next;
//交换头节点
curr2.next = curr1;
curr1.next = next;
head = curr2;
//交换后续节点
if(next == null || next.next == null) return head;
prev = curr1;
curr1 = next;
curr2 = curr1.next;
next = curr2.next;
while (curr1 != null && curr2 != null) {
curr2.next = curr1;
curr1.next = next;
prev.next = curr2;
if(next == null || next.next == null) return head;
prev = curr1;
curr1 = next;
curr2 = curr1.next;
next = curr2.next;
}
return head;
}
}
标签:24,head,ListNode,next,链表,curr1,curr2,prev,节点
From: https://blog.csdn.net/release_lonely/article/details/143894014