posts - 63, comments - 37, trackbacks - 0, articles - 0
  IT博客 :: 首页 :: 新随笔 :: 联系 ::  :: 管理

双链表的插入代码实现

Posted on 2006-06-21 21:46 Enjoy Life 阅读(576) 评论(0)  编辑 收藏 引用 所属分类: DS study
通过近20分钟的debug,终于把这个简单的代码实现,真是郁闷啊,发现指针的操作很容易出错.

//ListInsert_Dul.cpp

//This program is to insert a node into the DuLinkList

# include <stdlib.h>

# include <malloc.h>

# include <iostream.h>

# include <conio.h>

 

# define INIT_LENGTH 10

# define OK 1

# define ERROR 0

typedef int ElemType;

 

typedef struct DuLNode      //define DuLinkList structure

{   int data;

    struct DuLNode *prior;

    struct DuLNode *next;

}DuLNode,*DuLinkList;

 

 

 

int DuLinkLength(DuLNode *L){

    DuLNode *p;

    int i = 0;

    p = L;

    if(!L)

       return 0;

    else {

       while(p){

           i++;

           p = p->next;

       }

    }

    return i;

}

 

DuLNode *GetElemP_DuL(DuLNode *L, int i){

    int j;

    int k = 1;

    DuLNode *p;

    p = L;

    j = DuLinkLength(L);

   

    /*i=i±íʾ²åÔÚË«Á´±íµÄµÚÒ»¸öÔªËØλÖã¬j+1±íʾ

    *²åÔÚ×îºóÒ»¸öÔªËØÖ®ºó

    */

    if(i<2||i>j+1){

       return NULL;

    }

    else {

       while(k < i-1){

           k++;

           p = p->next;

       }

       return p;

    }

}

 

int ListInsert_DuL(DuLNode *L, int i, ElemType e){

    DuLNode *p, *s;

    if(!(p = GetElemP_DuL(L,i)))

       return ERROR;

    if(!(s = (DuLNode *)malloc(sizeof(DuLNode))))

       return ERROR;

    s->data = e;

    s->prior = p;

    s->next = p->next;

    p->next = s;

    return OK;

}

 

 

 

void main()               //main() function

{    int i,j,e;

     //DuLNode node[10];

     DuLNode *L,*p;

     int array[10]={5,8,12,18,25,30,37,46,51,89};

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

     L->next=NULL;

     L->data = array[0];

     L->prior=NULL;

     for (i=1;i<=9;i++)

     { 

     p=(DuLNode *)malloc(sizeof(DuLNode));

     p->data=array[i];

     L->next = p;

     p->prior = L;

     p->next = NULL;

     L = L->next;

     

     /*

     p->next=L->next;

     p->next->prior=p;

     L->next=p;

     */

     }

   

     for(i=1;i<=9;i++)

        L=L->prior;

     p = L;

    

     cout<<endl<<endl<<"ListInsert_Dul.cpp";

     cout<<endl<<"==================";

     cout <<endl<<endl<<"The old DuLNode is : ";  //output the old DuLinkList

     for(j=0;j<10;j++)

     {  

     cout<<p->data<<" ";

     p=p->next;

     }

     cout<<endl<<endl<<"Please input the location to insert (1--11) : ";

     cin>>i;

     cout<<"Please input the integer to insert (eg,58)  : ";

     cin>>e;

     if(ListInsert_DuL(L,i,e))

     {  cout <<endl<<"The new DuLNode is : ";

    p=L;

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

    {  

        cout<<p->data<<" ";

       p=p->next;

    }

     }

     cout<<endl<<endl<<"...OK!...";

     getch();

} //main() end

只有注册用户登录后才能发表评论。