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

#include
# include
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         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<<"链表长度为:"<data<     linkList* P=L->next;
    cout<<"链表数据为:";
    if(P==NULL){
        cout<<"链表为空";
    }
    while(P){
        cout<data<<" ";
        P=P->next;
    }
    cout< }
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->datadata){
            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 a={1,2,3};
    linkList *L2=createList();
    vector b={4,5,6};
    for(int i=0;i         insert(L1,a[i]);
    }
    for(int i=0;i         insert(L2,b[i]);
    }
     output(L1);
     output(L2);
     output(merge(L1,L2));
    return 0;

}

运行效果如下


你可能感兴趣的:(数据结构)