LeetCode24.两两交换链表中的节点
参考链接:代码随想录:LeetCode24.两两交换链表中的节点
我这里使用了3个变量进行暴力交换,简单快捷!但是有一点想不明白,return这里只能写dh->next,写返回head就结果不对了!但是后面又想明白了!这里是因为交换了节点,所以只能写dh->next
class Solution {
public:ListNode* swapPairs(ListNode* head) {ListNode* tmp=nullptr,*tmp1=nullptr,*tmp2=nullptr,*dh=new ListNode(0,head),*cur=nullptr;if(!head||!head->next){return head;}cur=dh;while(cur->next&&cur->next->next){tmp=cur->next;tmp1=cur->next->next;tmp2=cur->next->next->next;cur->next=tmp1;tmp1->next=tmp;tmp->next=tmp2;cur=tmp;}return dh->next;}
};