【题目】
将listNode中的元素两两为一组进行交换,要求
1、空间复杂度为线性,即必须在现有head的基础上对ListNode进行修改,不能另外开辟一个
2、不能仅仅交换两个节点中的数值,要交换节点本身
【思路】
指定两个变量,分别指向当前要交换的两个节点,进行交换,并将交换后的新的领头节点挂在head上即可
【Java代码】
public ListNode swapPairs(ListNode head){
if(head == null || head.next == null)
return head;
else{
ListNode start = head, end = head.next;
start.next = end.next;
end.next = start;
head = end;
ListNode r = head;
r = r.next;
start = end.next.next;
if(start != null)
end = start.next;
while(start != null && end != null){
start.next = end.next;
end.next = start;
r.next = end;
r = r.next.next;
start = end.next.next;
if(start != null)
end = start.next;
}
}
return head;
}