数据结构复习整理——线性表链式存储的基本操作

#include
#include
#include
#include
using namespace std;


typedef int ElemType;
struct LNode
{
    ElemType data;
    struct LNode *next;
};
//链表的建立
struct LNode* Build(struct LNode *head)
{
    struct LNode *p,*q;
    p=q=(struct LNode*)malloc(sizeof(struct LNode));
    p->next=NULL;
    int i=1;
    while(i<=11)
    {
        if(head==NULL)
            head=p;
        else
            q->next=p;
        q=p;
        p=(struct LNode*)malloc(sizeof(struct LNode));
        p->data=i;
        i++;
    }
    free(p);
    p=NULL;
    q->next=NULL;
    return head;
}




//链表的插入,其中i表示第i个数,m表示要插入的字符
struct LNode* LNode_insert(struct LNode *head,int i,ElemType n)
{
    int j=1;
    struct LNode *p1,*p2;
    p1=(struct LNode*)malloc(sizeof(struct LNode));
    p1=head;
    while(p1&&j     {
        p1=p1->next;
        j++;
    }
    p2=(struct LNode*)malloc(sizeof(struct LNode));
    p2->data=n;
    p2->next=p1->next;
    p1->next=p2;
    return head;
}
//链表的删除,其中j表示第j个数
struct LNode* LNode_delete(struct LNode *head,int i)
{
    int j=1;
    struct LNode *p,*q;
    p=head;
    while(p&&j     {
        p=p->next;
        j++;
    }
    q=p->next;
    p->next=p->next->next;
    free(q);
    return head;
}
//链表的遍历
void print(struct LNode *head)
{
    ElemType m;
    struct LNode *p;
    p=head;
    while(p->next!=NULL)
    {
        p=p->next;
        m=p->data;
        cout<     }
}
int main()
{
    int i,k,n;
    struct LNode *head;
    head=NULL;
    head=Build(head);
    print(head);
    cout<     cout<<"请输入你要插入数的位置i和数值n;";
    cout<     cin>>i>>n;
    head=LNode_insert(head,i,n);
    cout<<"插入后的结果为:";
    print(head);
    cout<     cout<<"请输入你要删除数的位置i;";
    cout<     cin>>k;
    head=LNode_delete(head,k);
    cout<<"删除后的结果为:";
    print(head);
    return 0;
}

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