初谈链表之单链表的实现。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int ElemType;
typedef int Status;
using namespace std;
typedef  struct Lnode
{
    ElemType           data;
    struct Lnode       *next;
} Lnode, *Linklist;
Status CreateList_L(Linklist &L,int n)
{
    L=(Linklist)malloc(sizeof(Lnode));
    L->next=NULL;
    Lnode *q = L;
    for (int i=n; i>0; --i)
    {
        Lnode *p=(Linklist) malloc(sizeof(Lnode));
        scanf("%d",&p->data);
        q->next = p;
        p->next =NULL;
        q = p;
    }
    return OK;
}  //createList_L

Status ListInsert_L(Linklist &L, int i, ElemType e)
{
    Lnode *p,*s;
    int j;
    p = L;
    j =0;
    while (p && j<i-1)
    {
        p=p->next;
        ++j;
    }
    if (!p || j>i-1) return ERROR;
    s=(Linklist)malloc(sizeof(Lnode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}//ListInsert_L

Status Listdelete_L(Linklist &L, int i, ElemType &e)
{
    Lnode *p,*s,*q;
    int j;
    p = L;
    j =0;
    while (p->next && j<i-1)
    {
        p=p->next;
        ++j;
    }
    if (!(p->next) || j>i-1) return ERROR;
    q=p->next;
    p->next=q->next;
    e=q->data;
    free(q);
    return OK;
}//Listdelete_L

int main()
{
    int e;
    Lnode *L;
    int i;
    cout<<"plase input 6 number to initilize linklist:"<<endl;
    CreateList_L(L,6);
    cout<<"The linked list is:"<<endl;
    Lnode *X=L;
    while(X ->next!= NULL)
    {
        X=X->next;
        printf("%d ",X->data);
    }
    cout<<endl;
    cout<<"plase input a element to insert:"<<endl;
    cin>>e;
    cout<<"plase input a position to insert:"<<endl;
    cin>>i;
    ListInsert_L(L,i,e);
    cout<<"after insert the linked list is:"<<endl;
    Lnode *X1=L;
    while(X1 ->next!= NULL)
    {
        X1=X1->next;
        printf("%d ",X1->data);
    }
    cout<<endl;
    cout<<"plase input the position to delete:"<<endl;
    cin>>i;
    Listdelete_L(L,i,e);
    cout<<"after delete the linked list is:"<<endl;
    Lnode *X2=L;
    while(X2 ->next!= NULL)
    {
        X2=X2->next;
        printf("%d ",X2->data);
    }
    cout<<endl;
    cout<<"The deleted element is :"<<e<<endl;
    return 0;
}

很简单,不想解释什么,有问题可以留言。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值