有序链表的合并(递归实现)
2010-07-21 16:09
369 查看
#include <cstdlib> #include <iostream> #include <vector> #include <ctime> #include <algorithm> using namespace std; typedef struct _NODE { int data; struct _NODE *next; _NODE(int val): data(val), next(NULL){} friend ostream& operator <<(ostream &os, const _NODE &nod) { return os << nod.data << "->"; } }NODE, *PTRNODE; void createList(PTRNODE &head, int num) { vector<int> val; srand((unsigned)time(NULL)); for(int i=0; i<num; i++) val.push_back(rand() % 100); sort(val.begin(), val.end()); PTRNODE curNode = NULL; for(int i=0; i<num; i++) { if(head == NULL) { head = new NODE(val[i]); curNode = head; } else { PTRNODE newNode = new NODE(val[i]); curNode->next = newNode; curNode = curNode->next; } } } PTRNODE mergeList(PTRNODE list1, PTRNODE list2) { PTRNODE head = NULL; if(list1 == NULL) return list2; if(list2 == NULL) return list1; if(list1->data < list2->data) { head = list1; head->next = mergeList(list1->next, list2); } else { head = list2; head->next = mergeList(list1, list2->next); } return head; } void display(PTRNODE head) { if(head == NULL) { cout << "empty list" << endl; return; } PTRNODE curNode = head; while(curNode != NULL) { cout << *curNode; curNode = curNode->next; } cout << endl; } int main(int argc, char *argv[]) { PTRNODE list1 = NULL, list2 = NULL; createList(list1, 10); createList(list2, 20); cout << "list1 is: " << endl; display(list1); cout << "list2 is: " << endl; display(list2); PTRNODE result = mergeList(list1, list2); cout << "merge result is: " << endl; display(result); system("PAUSE"); return EXIT_SUCCESS; }
相关文章推荐
- 递归实现合并两个有序链表
- 两个有序链表合并递归实现及非递归实现
- 合并两个有序链表,递归实现
- 递归实现两个有序链表的合并
- 递归实现合并两个有序链表成一个链表依然有序
- 合并两个有序链表(Java递归实现)
- 面试题17:合并两个有序链表,递归和非递归实现
- 用递归方法实现两个链表head1和head2各自有序,请把它们合并成一个链表仍然有序。(c/c++)
- 两个有序链表的合并(递归)
- Java实现两个有序链表的合并
- 合并有序链表,实现1+2+3...+n,要求不能使用乘除法、循环、条件判断、选择相关的关键字。
- 有序链表合并的递归和非递归算法
- 对两个有序的链表进行合并成一个一个有序链表(递归方法)
- 已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序。使用非递归方法以及递归方法。
- 链表的有序合并相关_C++实现
- c++实现双向有序链表的,增,删,查,合并
- 剑指offer--递归非递归合并两个有序链表
- 合并两个有序链表--实现1+2+3+....+n,时间复杂度为O(1)
- 已知两个链表head1 和head2 各自有序,请把它们合并成一个链表依然有序,要求用递归方法进行。
- 两有序链表合并为一个--递归与非递归两种方式