Swap Nodes in Pairs, Leetcode 解题笔记

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.

这种题思路都不难,无非是几个指针来回倒腾的问题,但是非常容易出错,面试时遇到此类题一定要耐心和细心。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode hold = new ListNode(0);
        hold.next = head;
        ListNode slow = hold;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            ListNode temp = fast.next.next;
            fast.next.next = slow.next;
            slow.next = fast.next;
            fast.next = temp;
            slow = fast;
            fast = slow.next;
        }
        return hold.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s