偶然发现上次做的题原来也是Divide and Conquer里面的一道orz所以又做了一道Linked List的题目:Swap Nodes in Pairs
24 | 37.4% | Medium |
这道题目要求是,给定一个单向链接表,对每两个相邻结点进行交换
For example,Given a linked list, swap every two adjacent nodes and return its head.
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.
看起来貌似不是很难,但是在设计算法的过程中总是出现小纰漏orz 比如...1->2->3->4交换完2->1之后就忘了把1的next指向4去了orz还有就是如果出现了节点数为单数的情况总是会把最后一个节点给忘了或者是把最后一个节点的上一个节点的next指到了NULL。而且还要考虑输入为NULL的情况,有好多细节需要考虑到。反正在整个过程中出现了许许多多的小问题就是了...
我个人的方式有点笨,是先把两个节点交换之后,把之前排在前面的节点的next指向下两个节点中排在较后的那个节点,比如1->2->3->4在对1、2进行交换之后就变成了2->1->4(同时3->4),然后再进行下一次交换,依次进行到最后。若节点数为单数,则将剩余的那个节点进行保留,不进行任何操作。
然后就...上代码吧
ListNode* swapPairs(ListNode* head) {
if(head==NULL)
{
return head;
}
else if(head->next==NULL)
{
return head;
}
else
{
ListNode* l=head;
ListNode* temp=l->next;
head=head->next;
while(l!=NULL&&l->next!=NULL)
{
if(temp->next!=NULL&&temp->next->next!=NULL)
{
l->next=temp->next->next;
}
else
{
l->next=temp->next;
}
ListNode* third=l;
l=temp->next;
temp->next=third;
if(l!=NULL)
{
temp=l->next;
//cout<<l->val<<endl;
}
}
return head;
}
}
看起来估计有点笨,这种算法应该算是比较简单粗暴的吧(想法比较简单粗暴...运行起来的复杂度什么的就不简单了orz)大家就不要嫌弃了orz