leetcode链接:
https://leetcode.cn/problems/swap-nodes-in-pairs/
方案一–遍历

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; }
ListNode right = head.next; ListNode left = head; ListNode rightTemp = null; ListNode leftTemp = null;
head = head.next;
while (right != null && left != null) { rightTemp = right.next;
right.next = left; left.next = rightTemp; if (leftTemp != null) { leftTemp.next = right; }
leftTemp = left; left = rightTemp;
if (left != null) { right = left.next; } } return head; } }
|
Accepted
- 55/55 cases passed (0 ms)
- Your runtime beats 100 % of java submissions
- Your memory usage beats 90.36 % of java submissions (38.9 MB)
分析
时间复杂度:
O( n )
空间复杂度:
O( 1 )
方案二–迭代
参考:
https://leetcode.cn/problems/swap-nodes-in-pairs/solution/dong-hua-yan-shi-24-liang-liang-jiao-huan-lian-bia/

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public ListNode swapPairs(ListNode head) { if(head==null || head.next==null) { return head; } ListNode tmp = head.next; head.next = swapPairs(tmp.next); tmp.next = head; return tmp; } }
作者:wang_ni_ma 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|