leetcode24.Swap Nodes in Pairs

题目要求

1
2
3
4
5
6
Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

翻译过来就是:将链表中相邻两个节点交换顺序,并返回最终的头节点。

思路

这题的核心解题思路在于如何不占用额外的存储空间,就改变节点之间的关系。我们设置了一个节点pre,为当前一个节点的前一个节点

1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode swapPairs(ListNode head) {
ListNode start = new ListNode(0);
start.next = head;
ListNode pre = start;
while(head!=null && head.next!=null){
pre.next = head.next;
head.next = pre.next.next;
pre.next.next = head;
pre = pre.next.next;
head = pre.next;
}
return start.next;
}