【题目】
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.
【分析】
一个节点用来记录head,不过在最后返回的时候,已经不是最初的head了,而是第二个节点(变成了新的head)
实际上是三个节点揭记录
cur记录交换两个节点的previous点,用来连接新的next值(pair里面的第二节点)
cur.next= swap(one ,two);
swap的过程:
1->2->next
1.1->mext=2.next: 1->next 2->next
2.next=1; : 2->1->next
【代码1】递归方法
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
【代码2】better understanding!!!!
注意:
1.用一个辅助指针来记录list的开头位置
2.最后返回start.next
public ListNode swapPairs(ListNode head) {
ListNode start = new ListNode(0); //make head no longer a special case
start.next = head;
for(ListNode cur = start; cur.next != null && cur.next.next != null; cur = cur.next.next) {
cur.next = swap(cur.next, cur.next.next);
}
<span style="color:#ff6666;">return start.next;</span>
}
private Listnode swap(ListNode next1, ListNode next2) {
next1.next = next2.next;
next2.next = next1;
return next2;
}