/**
* @author zhangruihao.zhang
* @version v1.0.0
* @since 2019/04/20
*/
public class LeetCode_24_108 {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution1 {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
//
ListNode first = head;
//
ListNode second = head.next;
//
ListNode cur = second.next;
//
first.next = cur;
second.next = first;
head = second;
ListNode pre = first;
//
first = cur;
second = cur == null || cur.next == null ? null : cur.next;
cur = second == null ? null : second.next;
while(first != null && second != null){
//
first.next = cur;
second.next = first;
pre.next = second;
pre = first;
//
first = cur;
second = cur == null || cur.next == null ? null : cur.next;
cur = second == null ? null : second.next;
}
return head;
}
}
class Solution2 {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
//
ListNode first = head;
//
ListNode second = head.next;
//
ListNode cur = second.next;
//
ListNode pre = null ;
//
first.next = cur;
second.next = first;
head = second;
while(true){
pre = first;
first = cur;
second = cur == null || cur.next == null ? null : cur.next;
cur = second == null ? null : second.next;
if(first == null || second == null){
break;
}
swap(pre,first,second,cur);
}
return head;
}
private void swap(ListNode pre,ListNode first,ListNode second,ListNode cur){
//
first.next = cur;
second.next = first;
pre.next = second;
}
}
}