1,问题描述
24. 两两交换链表中的节点
难度:中等
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:

1 2
| 输入:head = [1,2,3,4] 输出:[2,1,4,3]
|
示例 2:
示例 3:
提示:
- 链表中节点的数目在范围
[0, 100]
内
0 <= Node.val <= 100
2,初步思考
直接想到迭代法进行处理,其实像这种子问题都可以转为迭代或者递归处理
3,代码处理
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 35 36 37 38 39 40 41 42 43 44 45
| import support.ListNode;
public class _24两两交换链表中的节点 {
public ListNode swapPairs_recursion(ListNode head) { if(head==null||head.next==null)return head; ListNode newHead = head.next; head.next = swapPairs_recursion(newHead.next); newHead.next = head; return newHead; }
public ListNode swapPairs_iterator(ListNode head) { ListNode listNode = new ListNode(); listNode.next = head; ListNode tail = listNode; while (tail.next != null && tail.next.next != null) { ListNode before = tail; ListNode cur = tail.next; ListNode next = cur.next; before.next = next; cur.next = next.next; next.next = cur;
tail = cur; } return listNode.next; }
public static void main(String[] args) { _24两两交换链表中的节点 two = new _24两两交换链表中的节点(); ListNode listNode = two.swapPairs_iterator(ListNode.create(new int[]{1, 2, 3, 4, 5})); while (listNode != null) { System.out.println(listNode.val); listNode = listNode.next; } } }
|