/**24. Swap Nodes in Pairs
* @param head
* @return 交换相邻的两个节点值
*/
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode ret = new ListNode(-1);
ListNode add = ret;
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
ListNode next = fast.next;
add.next = fast;
fast.next = slow;
add = slow;
slow = next;
fast = slow.next;
}
if (fast == null) {
add.next = slow;
} else {
add.next = fast;
fast.next = slow;
slow.next = null;
}
return ret.next;
}
fast和slow指针,注意循环条件fast != null && fast.next != null
但是,题目要求只要交换值就可以了!!
/**24. Swap Nodes in Pairs
* @param head
* @return
*/
public ListNode swapPairs(ListNode head) {
ListNode ret = new ListNode(-1);
ret.next = head;
while(head != null){
int temp = head.val;
if (head.next != null) {
head.val = head.next.val;
head.next.val = temp;
head = head.next.next;
} else {
head = head.next;
}
}
return ret.next;
}