Leetcode: Swap Nodes in Pairs

来源:互联网 发布:学软件开发工资待遇 编辑:程序博客网 时间:2024/06/08 01:54

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.

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; } * } */public class Solution {    public ListNode swapPairs(ListNode head) {                if(head==null||head.next==null)return head;                ListNode n1=head;        ListNode n2=head.next;                while(n1!=null&&n2!=null)        {            int tmp = n1.val;            n1.val = n2.val;            n2.val = tmp;            n1 = n1.next.next;            if(n1!=null)n2 = n2.next.next;        }                return head;    }}


0 0