您的位置:首页 > Web前端 > Node.js

Leetcode || Swap Nodes in Pairs

2015-11-04 11:02 639 查看
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.

遍历索引,0,1,2,3…索引为偶数就和后面一个把值换了

package pack;

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null) {
return head;
}
ListNode p = head;
int i = 0;
while(p.next!=null) {

if(i%2==0) {
p.val = p.val ^ p.next.val;
p.next.val = p.val ^ p.next.val;
p.val = p.val ^ p.next.val;
}
i++;
p = p.next;
}
return head;
}
}

public class Main {

static public void  main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
n1.next = n2;
n2.next = n3;
n3.next = null;
System.out.println(n1.val);
System.out.println(n1.next.val);
System.out.println(n1.next.next.val);
new Solution().swapPairs(null);
System.out.println("--------------------");
System.out.println(n1.val);
System.out.println(n1.next.val);
System.out.println(n1.next.next.val);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode