题目:
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.
Subscribe to see which companies asked this question
ListNode* swapPairs(ListNode* head) {
if(head==nullptr || head->next==nullptr)
return head;
ListNode* nodeA=head;
ListNode* nodeB=nodeA->next;
ListNode* nodePrev = new ListNode(0);
head = head->next;
while(nodeB!=nullptr){
nodePrev->next = nodeB;
nodeA->next = nodeB->next;
nodeB->next = nodeA;
nodePrev=nodeA;
nodeA=nodePrev->next;
if(nodeA==nullptr)
break;
nodeB=nodeA->next;
}
return head;
}
解题思路:
也是不懂这个为什么叫分治。就是简单的链表局部翻转