【LeetCode】Swap Nodes in Pairs 解题报告

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指向链表的第一个元素。因为要把前两个元素翻转,所以用after保存第三个元素。

然后就是一系列翻转,我老是搞错。。好囧。

/**
 * 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

你可能感兴趣的:(LeetCode)