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.
JAVA
方法一
最简单的方法,就是直接交换相邻两个节点中的值,这样效率高还不容易出错,不过题中不允许。。。
方法二
设置四个指针P1,P2,P3,P4,指向相邻的4个节点,交换的目标是P2和P3,如果减少变量的话可以使用连续的.next来代替一些指针,不过会麻烦很多,而优化的效果非常有限,所以我还是选择了使用四个指针的方式。效率排在后30%,在排名中递归的速度又比较快,还是无法理解它快在哪里。。。
/**
* 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) {
ListNode result = new ListNode(0);
result.next = head;
ListNode p1,p2,p3,p4;
p1 = result;
while(p1.next != null){
p2 = p1.next;
p3 = p2.next;
if(p3 == null){
break;
}
p4 = p3.next;
p1.next = p3;
p3.next = p2;
p2.next = p4;
p1 = p2;
}
return result.next;
}
}