1. 原题链接

https://leetcode.com/problems/swap-nodes-in-pairs/description/

2. 题目要求

给定一个链表,交换相邻的两个结点。已经交换的结点,不再进行交换。

注意:所使用的空间大小固定

例如,1->2->3->4转换后为2->1->4->3

3. 题目思路

使用一个遍历指针current和两个辅助指针first、second,first保存current指针所在结点的后继结点,second保存current指针所在结点的后继的后继结点。

令first的后继指向second的后继,current的后继等于second,current后继的后继等于first,current等于first

4. 代码实现

public class SwapNodeInPairs24 {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
ListNode l6 = new ListNode(6);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6; ListNode ls1 = l1;
while (ls1 != null) {
System.out.print(ls1.val);
ls1 = ls1.next;
}
System.out.println(""); ListNode ls2 = swapPairs(l1);
while (ls2 != null) {
System.out.print(ls2.val);
ls2 = ls2.next;
} } public static ListNode swapPairs(ListNode head) {
ListNode headPointer = new ListNode(0);
headPointer.next = head;
ListNode current = headPointer; while (current.next != null && current.next.next != null) {
ListNode first = current.next;
ListNode second = current.next.next;
first.next = second.next;
current.next = second;
current.next.next = first;
current = first;
} return headPointer.next;
} public static class ListNode {
int val;
ListNode next; ListNode(int x) {
val = x;
}
}
}

  

05-11 17:24