
https://leetcode.com/problems/swap-nodes-in-pairs/
这题感觉迭代特别别扭,递归反而特别顺
递归
1 2 3 4 5 6 7 8
|
public ListNode (ListNode head) { if(head == null || head.next == null) return head; ListNode first = head, second = head.next; first.next = swapPairs(second.next); second.next = first; return second; }
|
迭代
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public ListNode (ListNode head) { if(head == null || head.next == null) return head; ListNode dummy = new ListNode(-1); ListNode first = dummy, second = head; while (second != null && second.next != null) { ListNode temp = second.next.next; second.next.next = second; first.next = second.next; second.next = temp; first = second; second = temp; } return dummy.next; }
|
近期评论