您的位置:首页 > 理论基础 > 数据结构算法

数据结构_单链表的插入与删除_C语言源代码

2014-07-11 22:17 423 查看
int ListInsert(LNode *&L, int i, int e)//插入

{

    int j=0;

    LNode *p=L;

    LNode *s=NULL;

    while(j<i-1)

    {

       p=p->next;

       ++j;

       if(NULL==p)

       {

        return 0;

       }

    }

    if(j>i-1)

    {

      return 0;

    }

    s=(LNode*)malloc(sizeof(LNode));

    s->data=e;

    s->next=p->next;

    p->next=s;

    return 1;

}

int ListDelete(LNode *&L,int i,int &e)//删除

{

    int j=0;

    LNode *p=L;

    LNode *q=NULL;

    while(j<i-1)

    {

      p=p->next;

      ++j;

      if(NULL==p)

      {

         return 0;

      }

    }

    if(j>i-1)

    {

      return 0;

    }

    q=p->next;

    e=q->data;

    p->next=q->next;

    free(q);

    return 1;

}

可运行的完整代码如下:

#include<stdio.h>

#include<stdlib.h>

typedef struct LNode

{

  int data;

  struct LNode *next;;

}LNode;

    

void InitList(LNode *&L)

{

     L=(LNode*)malloc(sizeof(LNode));

     L->next=NULL;

}

    

void  CreateListR(LNode *&L,int a[],int n)

{

      int i;

      LNode *r=L,*s=NULL;

      for(i=0;i<n;i++)

      {

        s=(LNode*)malloc(sizeof(LNode));

        s->data=a[i];

        r->next=s;

        r=s;

      }

      r->next=NULL;

}

void VisitList(LNode *L)

{

     LNode *s=L->next;

     while(NULL!=s)

     {

       printf("%d\n",s->data);

       s=s->next;

     }

}

void ListDelete(LNode *&L,int elem)

{

     

     LNode *s=L;

     LNode *q=NULL;

     while(s->next!=NULL) 

     {

       if(s->next->data==elem)

       {

        q=s->next;

        s->next=q->next;

        free(q);

        return ;

       }

       s=s->next;

     }

}

int ListInsert(LNode *&L, int i, int e)

{

    int j=0;

    LNode *p=L;

    LNode *s=NULL;

    while(j<i-1)

    {

       p=p->next;

       ++j;

       if(NULL==p)

       {

        return 0;

       }

    }

    if(j>i-1)

    {

      return 0;

    }

    s=(LNode*)malloc(sizeof(LNode));

    s->data=e;

    s->next=p->next;

    p->next=s;

    return 1;

}

int ListDelete(LNode *&L,int i,int &e)

{

    int j=0;

    LNode *p=L;

    LNode *q=NULL;

    while(j<i-1)

    {

      p=p->next;

      ++j;

      if(NULL==p)

      {

         return 0;

      }

    }

    if(j>i-1)

    {

      return 0;

    }

    q=p->next;

    e=q->data;

    p->next=q->next;

    free(q);

    return 1;

}

int main(void)

{

    const int N=5;

    int temp;

    int a
={2,3,4,5,6};

    LNode *L;

    InitList(L);

    CreateListR(L,a,N);

    VisitList(L);

    putchar(10);

   // ListDelete(L,6);//删除元素6

   // VisitList(L);

    if(ListInsert(L,2,10)==1)

    {

      VisitList(L);

    } 

    else

    {

       printf("input error!");

     

    }

    

    ListDelete(L,2,temp);

    putchar(10);

    VisitList(L);

    printf("===========%d\n",temp);

   

    

    

    system("pause");

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: