c++实现链表 增,删,查,合并

来源:互联网 发布:真正的绝望是什么知乎 编辑:程序博客网 时间:2024/06/03 04:20
#include <iostream>
# include<vector>
using namespace std;
struct linkList{
    int data;
    linkList* next;
};
linkList* createList(){//创建一个带头结点的链表,数据域记录链表长度,初始化为0
    linkList* L=new linkList();
    L->data=0;
    L->next=NULL;
    return L;
}
void insert(linkList*L,int elem){//插入一个节点
    linkList* Pre=L;
    linkList* P=L->next;
    while(P!=NULL&&P->data<elem){//寻找插入位置
        P=P->next;
        Pre=Pre->next;
    }
    linkList* current=new linkList();//新建节点并且插入
    current->data=elem;
    Pre->next=current;
    current->next=P;
    L->data+=1;//链表长度加1
    }
void deletel(linkList*L, int elem){
    linkList* Pre=L;
    linkList* P=L->next;
    while(P->data!=elem){//查找删除位置
         P=P->next;
         Pre=Pre->next;
    }
    Pre->next=P->next;
    delete(P);
    L->data--;
}
void output(linkList*L){
    cout<<"链表长度为:"<<L->data<<endl;
    linkList* P=L->next;
    cout<<"链表数据为:";
    if(P==NULL){
        cout<<"链表为空";
    }
    while(P){
        cout<<P->data<<" ";
        P=P->next;
    }
    cout<<endl;
}
linkList* check(linkList*L,int elem){
    linkList* P=L->next;
      while(P->data!=elem){//查找删除位置
         P=P->next;
    }
    return P;
}
linkList* merge(linkList* L1,linkList* L2){
     linkList* P1=L1->next;
     linkList* P2=L2->next;
     linkList* L3=new linkList();
     linkList* cur=L3;
     L3->data=L1->data+L2->data;
     while(P1&&P2){
        if(P1->data<P2->data){
            cur->next=P1;
            P1=P1->next;
            cur=cur->next;
        }
        else{
            cur->next=P2;
            P2=P2->next;
            cur=cur->next;
        }
     }
    while(P1){
         cur->next=P1;
         P1=P1->next;
         cur=cur->next;
    }
    while(P2){
          cur->next=P2;
            P2=P2->next;
            cur=cur->next;
    }
   return L3;
}
int main()
{
    linkList *L1=createList();
    vector<int> a={1,2,3};
    linkList *L2=createList();
    vector<int> b={4,5,6};
    for(int i=0;i<a.size();i++){
        insert(L1,a[i]);
    }
    for(int i=0;i<b.size();i++){
        insert(L2,b[i]);
    }
     output(L1);
     output(L2);
     output(merge(L1,L2));
    return 0;

}

运行效果如下


原创粉丝点击