面试题---两个有序单链表的合并
2017-11-04 10:42
393 查看
#include <iostream> using namespace std; struct node{ int value; struct node *next; }; struct node *head1; struct node *head2; void insert(struct node * &head,int value) { if(head == NULL) { head = new struct node; head->value = value; head->next = NULL; return; } struct node *p = new struct node; p->value = value; p->next = NULL; struct node *q = head; while(q->next != NULL) { q = q->next; } q->next = p; } struct node *merge(struct node *head1,struct node *head2) { if(head1 == NULL) return head2; if(head2 == NULL) return head1; struct node *head = NULL; if(head1->value > head2->value) { head = head2; head->next = merge(head1,head2->next); } else { head = head1; head->next = merge(head1->next,head2); } return head; } void print(struct node *head) { struct node *p = head; while(p != NULL) { cout<<p->value<<" "; p = p->next; } } int main() { head1 = NULL; head2 = NULL; insert(head1,1); if(head1 != NULL) cout<<"确实已经赋值了呀!\n"; insert(head1,3); insert(head1,5); insert(head1,9); insert(head1,11); insert(head1,16); insert(head1,18); insert(head2,6); insert(head2,10); insert(head2,12); insert(head2,13); insert(head2,15); insert(head2,18); cout<<"链表1:\n"; print(head1); cout<<endl; cout<<"链表2:\n"; print(head2); cout<<endl; cout<<"合并后为\n"; struct node *head = NULL; head = merge(head1,head2); if(head != NULL) print(head); cout<<endl; return 0; }
相关文章推荐
- 链表面试题-合并两个有序单链表(递归和非递归)
- 剑指Offer_面试题17_合并两个有序链表
- 两个有序单链表的合并&两个有序数组的合并
- 两个无序单链合并成一个有序单链表
- 两个有序单链表的合并
- 合并两个有序单链表
- Java单链表基本操作(八)--合并两个有序单链表
- 【C语言】两个有序单链表的合并
- 编程实现合并两个有序单链表
- 面试题:合并两个有序链表
- 写程序。设ha和hb分别是两个带头结点的非递减有序单链表的头指针,试设计算法,将这两个有序链表合并成一个非递增有序的单链表。要求使用原链表空间,
- 链表面试题之合并两个有序链表
- Java 非递归 和非递归方法 实现两个有序单链表的合并
- 链表面试题(七)---合并两个有序链表
- 合并两个有序单链表
- java编程实现将两个有序单链表LA,LB合并成新的LA
- 实现两个有序单链表的合并。要求:随机创建两个单链表,实现单链表的排序,再对两个有序单链表进行合并。
- 合并两个有序链表 经典面试题
- 数据结构 — 1. 两个非递减有序单链表合并为非递增有序单链表
- 两个有序单链表合并