链表建立、插入、删除、合并

//
// Created by dgm on 19-2-24.
//

//感觉最麻烦的还是指针移动次数
// 和元素的匹配,for循环经常搞不清楚
//循环i次还是i-1次
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct LNode{
    LNode()
    :next(NULL)
    {}
    ElemType data;
    LNode* next;
}LNode,*LinkList;
bool GetElem(LinkList L,int i,ElemType &e)
{
    auto p=L->next;
    unsigned int j=0;
    while(p&&j<i){
        p=p->next;
        j++;
    }
    if(!p||j>i)return false;
    e=p->data;
    return true;
}
bool Insert_Link_List(LinkList&L,unsigned int i,ElemType e)
{
    auto p=L;
    for(int t=0;t<i;t++)
    {
        p=p->next;
    }
    if(!p)return false;
    if(!p->next){
        p->next=new LNode();
        p=p->next;
        p->data=e;
        return true;
    }
    LinkList node=new LNode();
    node->next=p->next;
    node->data=e;
    p->next=node;
    return true;
}
bool Delete_Link_List(LinkList&L,unsigned int i,ElemType&e)
{
    auto p=L;
    for(int t=0;t<i;t++)p=p->next;
    if(!(p->next))return false;
    if(!(p->next->next))
    {
        e=p->next->data;
        free(p->next);
        return true;
    }
    auto q=p->next;
    p->next=q->next;
    e=q->data;
    free(q);
    return true;
}
void Create_Link_List(LinkList&L,unsigned int n)
{
    //L=new LNode();
    cout<<"cin "<<n<<" elements: "<<endl;
    for (int i = 0; i < n; ++i) {
//        LinkList temp=new LNode();
//        cin>>temp->data;
//        temp->next=L->next;     //每次都在头指针后插入
//        L->next=temp;           //所以先插入的远离头指针
        ElemType e;               
        cin>>e;
        Insert_Link_List(L,i,e);   //i越大,离头指针越远
    }                               //先插入的在前面

}
void Print_Link_List(LinkList L)
{
    auto p=L->next;
    while(p)
    {
        cout<<p->data<<" ";
        p=p->next;
    }
}
void Merge_Link_List(LinkList La,LinkList Lb,LinkList&Lc)
{
    auto pa=La->next;
    auto pb=Lb->next;
    auto pc=Lc=La;
    while(pa&&pb)
    {
        if(pa->data<=pb->data)
        {
            pc->next=pa;
            pc=pa;
            pa=pa->next;
        }
        else
        {
            pc->next=pb;
            pc=pb;
            pb=pb->next;
        }
    }
    pc->next=pa?pa:pb;
    free(Lb);
}
int main()
{
    LinkList L=new LNode();
    Create_Link_List(L,6);
    Print_Link_List(L);
    cout<<endl;
    Insert_Link_List(L,3,'9');
    Print_Link_List(L);
    cout<<endl;
    ElemType e;
    Delete_Link_List(L,2,e);
    Print_Link_List(L);
    cout<<endl;
    GetElem(L,3,e);
    cout<<e<<endl;

    LinkList La=new LNode();
    LinkList Lb=new LNode();
    Create_Link_List(La,3);
    Create_Link_List(Lb,4);
    Merge_Link_List(La,Lb,L);
    Print_Link_List(L);
    cout<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37613112/article/details/87913274
今日推荐