两两交换链表中的节点
题目介绍
两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
1 2
| 输入:head = [1,2,3,4] 输出:[2,1,4,3]
|
示例 2:
示例 3:
提示:
- 链表中节点的数目在范围
[0, 100] 内
0 <= Node.val <= 100
进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
题目解法
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package algorithm;
public class SwapNodesInPairs {
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) { return head; }
ListNode left = head; ListNode right = head.next; ListNode next = right.next; ListNode prev = new ListNode(0, head); int headIndex = 0; while (right != null) { left.next = next; right.next = left;
prev.next = right; prev = left; if (headIndex == 0) { head = right; headIndex ++; }
if (next != null) { left = next; right = next.next; } else { break; } if (right != null) { next = right.next; } }
return head; }
public static void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); n1.next = n2; ListNode n3 = new ListNode(3); n2.next = n3; ListNode n4 = new ListNode(4); n3.next = n4; print(swapPairs(n1));
ListNode n5 = null; print(swapPairs(n5));
ListNode n6 = new ListNode(1); print(swapPairs(n6)); }
private static void print(ListNode head) { while (head != null) { System.out.print(head.val); head = head.next; } System.out.println(); }
public static class ListNode { int val; ListNode next;
ListNode() { }
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; } } }
|
打印:
思路:
这道题居然没有想到可以递归,递归的代码少到可怜;然后自己写出来的是迭代,当然和官方答案比,代码量还是稍显多。