单链表的插入算法---------共享

单链表的插入算法---------共享

//单链表的插入算法
# include <stdlib.h>
# include <malloc.h>
# include <iostream.h>
# include <conio.h>

# define INIT_LENGTH 10
# define OK 1
# define ERROR 0

typedef struct LNode                        //定义结点(Lnode)结构
{        int data;
        struct LNode *next;
}LNode,*Linklist;

int ListInsert_L(Linklist &L,int i,int e)      //插入函数
{   LNode *p=L;
    int j=0;
    while(p&&j<i-1)                   //find the location
    {  p=p->next;
       ++j;
    }
    if(!p||j>i-1)                //out of location
    {  cout<<"Errer! The location is illegal!"<<endl;
       return (ERROR);
    }
    LNode *s;
    s=(Linklist)malloc(sizeof(LNode));        //create new LNode
    s->data=e;
    s->next=p->next;
    p->next=s;
    return (OK);
} //ListInsert_L() end

void main()                                //主函数
{    int i,j,e;
     LNode node[10];
     LNode *L,*p;
     int array[INIT_LENGTH+1]={5,8,12,18,25,30,37,46,51,89};
     L=(Linklist)malloc(sizeof(LNode));
     L->next=NULL;
     for (i=10;i>0;i--)
     {          p=(Linklist)malloc(sizeof(LNode));
         p->data=array[i-1];
         p->next=L->next;
         L->next=p;
     }
     p=L;                                         //插入前打印单链表
     cout<<endl<<endl<<"ListInsert_L.cpp";
     cout<<endl<<"================";
     cout <<endl<<endl<<"The old LNode is : ";
     for(i=0;i<INIT_LENGTH;i++)
     {   p=p->next;
         cout<<p->data<<" ";
     }
     cout<<endl<<endl<<"Please input the location to insert (1--11): ";
     cin>>j;
     cout<<"Please input the integer to insert (eg,58) : ";
     cin>>e;
     if(ListInsert_L(L,j,e))
     {  cout <<endl<<"The new LNode is : ";
        p=L;                                          //插入后打印单链表
        for(i=0;i<11;i++)
        {   p=p->next;
            cout<<p->data<<" ";
        }
     }
     cout<<endl<<endl<<"...OK!...";
     getch();
}



文章来自: hackbase
引用通告: 查看所有引用 | 我要引用此文章
Tags:
评论: 1 | 引用: 0 | 查看次数: 9049
  • 1
yeye9 [2006-12-25 03:00 PM]
学习了。
  • 1
发表评论
昵 称:
密 码: 游客发言不需要密码.
验证码: 验证码
内 容:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 2000 字 | UBB代码 开启 | [img]标签 关闭