力扣24
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
链表题还是做太少了呀
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode post = head, pre = post, temp = null; head = head.next; while (pre != null && pre.next != null){ pre = post.next.next; post.next.next = post; if (temp != null) temp.next = post.next; temp = post; post = pre; } temp.next = pre; return head; }
|
像temp这种要延迟一轮的,可以把初始值设为null,然后while循环中if (temp != null),可以达到延迟一轮的效果
或者是while的周期安排得更好一点,比如下面大佬写的
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public ListNode swapPairs2(ListNode head) { ListNode pre = new ListNode(0); pre.next = head; ListNode temp = pre; while(temp.next != null && temp.next.next != null) { ListNode start = temp.next; ListNode end = temp.next.next; temp.next = end; start.next = end.next; end.next = start; temp = start; } return pre.next; }
|
周期就安排的很好
temp->start->end,start和end是要交换的,temp永远在他们后面一个,方便对start这个节点操作
而上面我写的周期为
断裂的两个节点 post->b->pre,要交换的是post和b,这时候就要用temp将断裂的连上post,比较憨
其他链表类型的题目点击这里