2.3-线性表的链接实现

// DataStructTest.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream.h>
#include 
<malloc.h>

typedef 
struct node * pointer;
struct node
{
    
int data;
    pointer next;
}
;
typedef pointer lklist;
lklist head
=NULL;                        //表头

//初始化链表
lklist initiate_lklist()
{
    lklist t
=(lklist)malloc(sizeof(node));
    t
->next=NULL;
    
return t;
}

//求表长
int length_lklist(lklist head)
{
    
int i=0;
    lklist p
=head;
    
while(p->next!=NULL)
    
{
        i
++;
        p
=p->next;
    }

    
return i;
}

//按序号查找
pointer find_lklist(lklist head,int index)
{
    lklist p
=head;
    
int j=0;
    
while(p->next!=NULL && j<index)
    
{
        j
++;
        p
=p->next;
    }

    
if (j==index)
        
return p;
    
else
        
return NULL;
}

//定位
int locate_lklist(lklist head,int value)
{
    
int index=0;
    lklist p
=head;
    
while(p->next!=NULL && value!=p->data)
    
{
        p
=p->next;
        index
++;
    }

    
if (p!=NULL && p->data==value)
        
return index;
    
else
        
return NULL;

}

//删除
void delete_lklist(lklist head,int index, char * error)
{
    lklist p
=NULL;
    lklist pNext
=NULL;
    p
=find_lklist(head,index-1);                    //找到前驱
    if (p!=NULL)
    
{
        pNext
=p->next->next;
        free(p
->next);
        p
->next=pNext;
    }

    
else
    
{
        error
="不存在此结点";
    }

}

//新增
void insert_lklist(lklist head,int value,int index,char * error)
{
    lklist p
=NULL;
    lklist pNext
=NULL;
    lklist pNew
=NULL;
    p
=find_lklist(head,index-1);
    
if (p!=NULL)
    
{    
        pNext
=p->next;
        pNew
=(lklist)malloc(sizeof(node));
        p
->next=pNew;
        pNew
->next=pNext;
        pNew
->data=value;
    }

    
else
    
{
        error
="不存在此结点";
    }

}

//显示
void display(lklist head)
{
    lklist p
=head;
    
int i=0;
    p
=p->next;                //指向第一个结点
    while(p!=NULL)
    
{
        i
++;
        cout
<<""<<i<<"个元素的值为:"<<p->data<<endl;
        p
=p->next;
    }

}

int main(int argc, char* argv[])
{
    
char * error=NULL;
    head
=initiate_lklist();
    pointer p
=NULL;
    
int i=0;
    
//新增
    cout<<"新增4个结点"<<endl;
    insert_lklist(head,
1,1,error);
    insert_lklist(head,
2,2,error);
    insert_lklist(head,
3,3,error);
    insert_lklist(head,
4,4,error);
    display(head);
    
//表长
    i=length_lklist(head);
    cout
<<"表长为:"<<i<<endl;
    
//按序号查找
    p=find_lklist(head,2);
    cout
<<"第二个元素的值为:"<<p->data<<endl;
    
//定位
    cout<<"定位测试值为3的元素在链表中的位置为:"<<locate_lklist(head,3)<<endl;
    
//删除
    cout<<"删除第3个元素:"<<endl;
    delete_lklist(head,
3,error);
    display(head);
    
return 0;
}

posted @ 2007-06-25 09:11  吴东雷  阅读(388)  评论(0编辑  收藏  举报