写正确函数需要注意的地方:链表的合并排序
2014-03-04 12:12
211 查看
Node* mergeSort(Node* head, int length) { if(length==0) return NULL; if(length==1) { head->pNext=NULL;//一定要赋值为NULL,否则可能出现死循环。 return head; } int halflength=length/2; Node* halfp=head; for(int i=0;i<halflength;++i) halfp=halfp->pNext; Node* p1=mergeSort(head, halflength); Node* p2=mergeSort(halfp,length-halflength); //merge部分 Node* result=NULL; if(p1->value>p2->value) { result=p2; p2=p2->pNext; } else { result=p1; p1=p1->pNext; } Node* tail=result; while(p1!=NULL && p2!=NULL) { if(p1->value>p2->value) { tail->pNext=p2; tail=tail->pNext; p2=p2->pNext; } else { tail->pNext=p1; tail=tail->pNext; p1=p1->pNext; } } tail->pNext=(p1==NULL?p2:p1); return result; } Node* mergeSort(Node* head) { if(head==NULL || head->pNext==NULL) return head; int length=0; Node* cur=head; for(;cur!=NULL;cur=cur->pNext) ++length; mergeSort(head,length); } int _tmain(int argc, _TCHAR* argv[]) { srand(time(0)); int size=rand()%20; Node* head=NULL; for(int i=0;i<size;++i) addHead(rand()%50,head); print(head); print(mergeSort(head)); getchar(); return 0; }
相关文章推荐
- 写正确函数需要注意的地方:两个非降序链表的并集,1>2>3和2>3>5合并为1>2>3>5。
- 写正确函数需要注意的地方:两个有序链表的合并
- 写正确函数需要注意的地方:链表的逆转,递归与非递归
- 写正确函数需要注意的地方:链表的及时终止冒泡排序
- 写正确函数需要注意的地方:快速排序
- 写正确函数需要注意的地方:strstr
- 写正确函数需要注意的地方:int转char*, char* 转int。
- 写正确函数需要注意的地方:输入两个整数n和m,从数列1,2,3,...n中随意取几个数,使其和为m,列出所有可能组合
- 写正确函数需要注意的地方:在字符串中找出连续最长的数字串,并把这个串的长度返回
- 写正确函数需要注意的地方:二分查找
- 写正确函数需要注意的地方:最大堆的创建与堆排序
- 写正确函数需要注意的地方:子数组的最大和
- 写正确函数需要注意的地方:给定一个十进制整数N,计算从1开始到N的所有整数出现的“1”的个数
- 写正确函数需要注意的地方:最长递减子序列
- 写正确函数需要注意的地方:奇偶数分开,左边偶数,右边奇数。
- 写正确函数需要注意的地方:输入一个字符串,打印出该字符串中字符的所有排列
- 写正确函数需要注意的地方:二叉树非递归中序遍历
- 写正确函数需要注意的地方:翻转句子中单词的顺序。
- 写正确函数需要注意的地方:快速返回斐波那契数的第n项
- 写正确函数需要注意的地方:两个序列a,b,大小都为n,序列元素的值为任意整数,无序;要求通过交换a,b中的元素,使序列a元素的和与序列b元素的和之间的差最小