题目描述: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.
题目大意是给定两个链表,依次交换相邻两个节点,直至结尾。注:不能直接交换两个节点的值(言下之意必须通过指针的变化来完成)
思路:我的思路很简单,设置三个指针,cur,p,temp。cur总是指向新链表的最后一个节点,它主要用来添加新节点;p指向链表中的每个奇数节点,每交换一对节点,p右移一次;temp的主要功能是保证不断链以及作为每次交换之后最后加入的节点指针,在每次交换的时候为了保证p能够顺利右移,并且cur能找到需要新添加的这个奇数节点(每对节点中,奇数节点总是比偶数节点更晚加入到新链表中),需要设置这个临时指针,如果你还是不理解,画个简图将会一目了然。
此外还需要考虑一些特殊情况,其中主要是链表为空,只有一个节点,节点个数为奇数等。最后别忘了将最后加入的节点指向空!
下面是参考代码:
public ListNode swapPairs(ListNode head) {
ListNode res = null;
if (head == null)
return null;
if (head.next == null)
return head;
ListNode cur = head.next;//保存当前节点的指针
ListNode p = head;//保存奇数节点的指针
ListNode temp = null;//在p右移之前暂存p,保证cur能指向它
while(p != null) {
if(res == null) {
res = head.next;
temp = p;
p = cur.next;
cur.next = temp;
cur = temp;
} else {
temp = p;
if(temp.next != null) {//奇数个节点时下面会出现空指针
cur.next = p.next;
cur = p.next;//此处会出现空指针
p = cur.next;
cur.next = temp;
cur = temp;
} else
break;
}
}
if(temp.next == null)
cur.next = temp;
else
temp.next = null;//最后一个节点指向空,切记!
return res;
}