成对的交换链表的节点 Swap Nodes in Pairs

问题:node

Given a linked list, swap every two adjacent nodes and return its head.spa

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.指针

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.code

解决:it

① 直接交换便可。io

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { //4ms
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null && fast.next != null && fast.next.next != null){//避免空指针异常
            int tmp = slow.val;
            slow.val = fast.val;
            fast.val = tmp;
            slow = fast.next;
            fast = slow.next;
        }
        int tmp = slow.val;//处理最后两个数
        slow.val = fast.val;
        fast.val = tmp;
        return head;
    }
}ast

② class

class Solution {//5ms
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode header = new ListNode(-1);
        header.next = head;
        ListNode cur = header;
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != null && fast != null){
            slow.next = fast.next;
            fast.next = slow;
            cur.next = fast;
            cur = slow;
            slow = slow.next;
            if(slow != null)fast = slow.next;
        }
        return header.next;
    }
}List

相关文章
相关标签/搜索