LeetCode24:
    给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    1. class ListNode {
    2. int val;
    3. ListNode next;
    4. ListNode() {
    5. }
    6. ListNode(int val) {
    7. this.val = val;
    8. }
    9. ListNode(int val, ListNode next) {
    10. this.val = val;
    11. this.next = next;
    12. }
    13. }
    14. class Solution {
    15. public ListNode swapPairs(ListNode head) {
    16. if (head == null) {
    17. return head;
    18. }
    19. ListNode pre = head;
    20. ListNode cur = head.next;
    21. ListNode temp = null;
    22. if (cur != null){
    23. temp = cur;
    24. }else {
    25. temp = head;
    26. }
    27. while (cur != null) {
    28. pre.next = cur.next;
    29. cur.next = pre;
    30. pre = pre.next;
    31. cur = cur.next;
    32. cur = cur.next;
    33. if (cur == null) {
    34. break;
    35. }
    36. cur = cur.next;
    37. }
    38. return temp;
    39. }
    40. }