赞
踩
问题描述:
- #include<iostream>
- using namespace std;
- const int MaxSize = 100;
- typedef struct{
- int *data;
- int length;
- }SeqList;
-
- //顺序表初始化
- void InitList(SeqList &L)
- {
- L.data = new int[MaxSize];
- L.length=0;
- }
- //创建顺序表
- void CreatList(SeqList &L)
- {
- int n;
- cout<<"创建顺序表元素个数:" ;
- cin>>n;
- L.length = n;
- for(int i=0;i<n;i++){
- cin>>L.data[i];
- }
- }
- //打印顺序表
- void PrintList(SeqList L){
- for(int i=0;i<L.length;i++)
- {
- cout<<L.data[i]<<" ";
- }
- cout<<endl;
- }
- //顺序表的合并-无序
- void MergeList(SeqList &La,SeqList &Lb)
- {
- for(int i=0;i<Lb.length;i++)
- {
- int flag=1;
- for(int j=0;j<La.length;j++)
- {
- if(Lb.data[i]==La.data[j])
- {
- flag=0;
- }
- }
- if(flag==1){
- La.data[La.length++]=Lb.data[i];
- }
- }
- }
- int main()
- {
-
- SeqList Lista,Listb;
- InitList(Lista);
- InitList(Listb);
-
- cout<<"ListA:";
- CreatList(Lista);
- cout<<"ListB:";
- CreatList(Listb);
- cout<<"合并线性表:";
- MergeList(Lista,Listb);
- PrintList(Lista);
- return 0;
- }
程序运行结果:
问题描述:
代码实现如下:
- #include<iostream>
- using namespace std;
- typedef struct Node{
- int data;
- struct Node* next;
- }LinkList;
- //尾插创建单链表
- struct Node* creatlist(){
- Node* head = new Node;
- head->next = nullptr;
-
- Node* rear = head;
- Node* s = nullptr;
- int n;
- cout<<"创建链表的长度:";
- cin>>n;
- cout<<"输入链表的值:" ;
- for(int i=0;i<n;i++){
- Node* s = new Node;
- cin>>s->data;
- rear->next = s;
- rear = s;
- }
- rear->next = nullptr;
- return head;
- }
- //打印单链表
- void printfList(Node *head){
- Node* pre = head->next;
- while(head){
- cout<<pre->data<<" ";
- pre = pre->next;
- }
- cout<<endl;
- }
- //用链表实现有序表的合并
- Node* MergeList(Node* head1,Node* head2){
- Node *la,*lb,*lc;
- la = head1->next;
- lb = head2->next;
- Node* dummyhead = new Node();
- Node* tail = dummyhead;
- while(la && lb ){
- if(la->data < lb->data ){
- tail->next = la;
- tail = la;
- la = la->next;
- }else{
- tail->next = lb;
- tail = lb;
- lb = lb->next;
- }
- }
- if(la){
- tail->next = la;
- }
- if(lb){
- tail->next = lb;
- }
- return dummyhead;
- }
- int main(){
- Node* List1head = creatlist();
- Node* List2head = creatlist();
- Node* ret = MergeList(List1head,List2head);
- printfList(ret);
- return 0;
- }
程序运行结果:
最近开始复习前面的知识,没有时间刷leetcode的题目(想一道好费劲
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/700654
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。