【LeetCode】Swap Nodes in Pairs解題報告

1449 ワード

Swap Nodes in Pairs
[LeetCode]
https://leetcode.com/problems/swap-nodes-in-pairs/
Total Accepted: 95332 Total Submissions: 270806 Difficulty: Easy
Question
Given a linked list, swap every two adjacent nodes and return its head.
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.
Ways
一番嫌いなのはこの針が往復する問題です!
まず自分でヘッダを定義し、firstはこのヘッダanswerを指し、nextはチェーンテーブルの最初の要素を指す.最初の2つの要素を反転させるため、afterで3番目の要素を保存します.
それから一連の反転で、私はいつも間違っています.好囧.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        ListNode answer=new ListNode(0);
        answer.next=head;
        ListNode first=answer;
        ListNode next=answer.next;
        ListNode after;
        while(next!=null && next.next!=null){
            after=next.next.next;
            next.next.next=next;
            first.next=next.next;
            next.next=after;
            first=next;
            next=after;
        }
        return answer.next;
    }
}

AC:1ms
Date
2016/5/1 20:24:22