# LeetCode 24. 两两交换链表中的节点 Swap Nodes in Pairs

### 5-4 复杂的穿针引线 Swap Nodes in Pairs

##### 题目: LeetCode 24. 两两交换链表中的节点

// 24. Swap Nodes in Pairs
// https://leetcode.com/problems/swap-nodes-in-pairs/description/
// 时间复杂度: O(n)
// 空间复杂度: O(1)
public class Solution {

while(p.next != null && p.next.next != null ){
ListNode node1 = p.next;
ListNode node2 = node1.next;
ListNode next = node2.next;
node2.next = node1;
node1.next = next;
p.next = node2;
p = node1;
}

}

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4};

}
}

// Definition for singly-linked list.
public class ListNode {

public int val;
public ListNode next = null;

public ListNode(int x) {
val = x;
}

// 根据n个元素的数组arr创建一个链表
// 使用arr为参数，创建另外一个ListNode的构造函数
public ListNode (int[] arr){

if(arr == null || arr.length == 0)
throw new IllegalArgumentException("arr can not be empty");

this.val = arr[0];
ListNode curNode = this;
for(int i = 1 ; i < arr.length ; i ++){
curNode.next = new ListNode(arr[i]);
curNode = curNode.next;
}
}

// 返回以当前ListNode为头结点的链表信息字符串
@Override
public String toString(){

StringBuilder s = new StringBuilder("");
ListNode curNode = this;
while(curNode != null){
s.append(Integer.toString(curNode.val));
s.append(" -> ");
curNode = curNode.next;
}
s.append("NULL");
return s.toString();
}
}


05-25 197

01-22 1254
04-09 447
04-10 328
06-27 504
04-05 383
08-12 897
06-08 942
06-27 6487