24. swap nodes in pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

1
Given 1->2->3->4, you should return the list as 2->1->4->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

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode lead = dummy;
while (head != null && head.next != null) {
lead.next = head.next;
head.next = head.next.next;
lead.next.next = head;
lead = head;
head = head.next;
}
return dummy.next;
}
}