public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head.next;
ListNode first = head;
ListNode second = head.next;
while (first != null && second != null) {
ListNode nextRound = second.next;
second.next = first;
// 第一种情况 到末尾偶数个节点
if (nextRound == null) {
first.next = nextRound;
break;
// 第二种情况 到末尾奇数个节点
} else if (nextRound != null && nextRound.next == null) {
first.next = nextRound;
break;
// 第三种情况,后面还有多个节点
} else {
first.next = nextRound.next;
}
first = nextRound;
second = nextRound.next;
}
return dummy.next;
}
【leetcode24】两两交换链表中节点
最新推荐文章于 2024-07-25 16:40:31 发布