题目
题解
代码
/** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */
public class code24 {
public static ListNode swapPairs(ListNode head) {
ListNode h = new ListNode(-1);
h.next = head;
ListNode pre = h;
while (pre.next != null && pre.next.next != null) {
ListNode node1 = pre.next;
ListNode node2 = node1.next;
ListNode later = node2.next;
pre.next = node2;
node2.next = node1;
node1.next = later;
pre = node1;
}
return h.next;
}
public static ListNode createList() {
ListNode head = new ListNode(1);
ListNode cur = head;
for (int i = 2; i <= 10; i++) {
cur.next = new ListNode(i);
cur = cur.next;
}
return head;
}
public static void print(ListNode node) {
if (node == null) {
return;
}
ListNode current = node;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
ListNode head = createList();
print(head);
ListNode res = swapPairs(head);
print(res);
}
}