题目
思路
- 思路一:使用头插法来翻转节点
-
代码
public ListNode swapPairs(ListNode head) {ListNode dummy = new ListNode(0);dummy.next = head;ListNode prv = dummy;while (head != null && head.next != null) {ListNode nex = head.next;head.next = nex.next;nex.next = prv.next;prv.next = nex;//重置节点prv = head;head = head.next;}return dummy.next;}//自己的递归public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode nextHead = swapPairs(head.next.next);ListNode nHead = reverse(head, 1);nHead.next.next = nextHead;return nHead;}public ListNode reverse(ListNode head, int i) {if (i == 2) {return head;}ListNode nHead = reverse(head.next, i + 1);head.next.next = head;head.next = null;return nHead;}//别人的递归public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode next = head.next;head.next = swapPairs(head.next.next);next.next = head;return next;}
