Middle-题目25:24. Swap Nodes in Pairs

题目原文:
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.
题目大意:
给一个单链表,两两交换相邻节点。
题目分析:
用Two Pointers,分别指向头结点和第二个节点,每次移动两步,注意处理结点个数为奇数(最后一次的时候p2->next为空,再取next会报错)的特殊情况。
源码:(language:java)

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) // This list has only 0 or 1 node.
            return head;    
        ListNode l1=head,l2=head.next;
        while(l1!=null && l2!=null) { 
            int temp=l1.val;
            l1.val=l2.val;
            l2.val=temp;
            l1=l1.next.next;
            l2=l2.next;
            if(l2==null)
                break;
            else
                l2=l2.next;
        }
        return head;
    }
}

成绩:
0ms,beats 13.35%,众数0ms,86.65%
Cmershen的碎碎念:
这题很水,不知道为什么出现在Middle里面。

你可能感兴趣的:(Middle-题目25:24. Swap Nodes in Pairs)