关于leetcode:24-Swap-Nodes-in-Pairs

63次阅读

共计 550 个字符,预计需要花费 2 分钟才能阅读完成。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) {this.val = val;}
 *     ListNode(int val, ListNode next) {this.val = val; this.next = next;}
 * }
 */
class Solution {public ListNode swapPairs(ListNode head) {if(head == null || head.next == null) return head;
        ListNode temp = head.next;
        head.next = temp.next;
        temp.next = head;
        head = temp;
        ListNode pre = head.next;
        if (pre.next == null)
            return head;
        ListNode cur = pre.next;
        while(cur != null && cur.next != null) {
            temp = cur.next;
            pre.next = temp;
            cur.next = temp.next;
            temp.next = cur;
            pre = cur;
            cur = pre.next;
        }
        
        return head;
    }
}

正文完
 0