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.
题目理解:不要交换链表节点的值,而是直接交换链表相邻的(奇数+偶数)节点对。时间复杂度控制在O(n),空间复杂度控制在O(1)。
题目思路:记录当前节点的父和祖先节点位置,每遍历到一组节点对,就触发一次交换。
import java.lang.Math;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode swapPairs(ListNode head) {
boolean ifrecord=true;
ListNode pparent=new ListNode(0);
//LeetCode里的链表从第一个节点就是开始保存数据了,所以要新建一个节点来抓住输入链表的头。
pparent.next=head;
ListNode parent=null,Pchild=head;
head=pparent; //把head重定义了,haed不是head了
while(Pchild!=null){ //只要还没扫到链表末尾
if(ifrecord==true){
//布尔类型来标记当前是否进到了新的一组,要交换的俩节点里,ifrecord==true,将当前节点记为父节点。
parent=Pchild;
}else{
/**
* 用1,2举例,设pparent->0,1,2,3,4; parent->1,2,3,4;Pchild->2,3,4;
*/
Pchild=parent; //Pchild->1,2,3,4;parent->1,2,3,4;pparent->0,1,2,3,4;
parent=parent.next; //Pchild->1,2,3,4;parent->2,3,4;pparent->0,1,2,3,4;
Pchild.next=parent.next;//Pchild->1,3,4;parent->2,3,4;pparent->0,1,2,3,4;
parent.next=Pchild; //Pchild->1,3,4;parent->2,1,3,4;pparent->0,1,2,3,4;
pparent.next=parent; //Pchild->1,3,4;parent->2,1,3,4;pparent->0,2,1,3,4;
pparent=Pchild; //Pchild->1,3,4;parent->2,1,3,4;pparent->1,3,4;
//至此12交换完毕,下一轮交换34
}
Pchild=Pchild.next;
ifrecord=(!ifrecord);
}
return head.next;
}
}