2.2-线性表的顺序实现

我是一名自考生,也是一个普通的程序员.数据结构这门课对我来说是非常重要的,但是因为我是学自考的,以前上学的时候也没有学过这门课,现在也没有人辅导,所以只能自学.我记得李开复曾经说过,"计算机这门课有些课程自学起来是相当困难的,比如数据结构和算法".这点我深有感触,因为我也曾经试图自学这门课,但每每都会遇到很多的挫折,有些问题对我来说相当有困难,比如我印象最深的那个字符串匹配算法,我到现在也不能很好的掌握.而且因为困难太多,所以每次都没有学完.
现在自考课程里有这门课,我就可以有动力坚持学完了,呵呵.这本书不是很厚,讲的算法也不是很多,但是我手里没有练习册,只能够凭自己看书自学,我想在我学习的过程中还会遇到问题,但是我会努力的解决掉它,我想应该还有很多像我一样的自考生,因为数据结构这门课头痛.书上的例子是用类C语言描述的,所以我决定将其改写能在VC++下运行的代码,其中有些代码可能和书上的不符,一方面是语言上的差别,一方面有些简单的我可能没有看书,而是凭自己的理解做的.
以后我会陆续的编写书上的代码,如果时间允许我还会尝试着做课后的习题,在记录自己学习历程的同时,也为其它的自考生提供一个可运行的版本.

因为是在VC6.0下编写的代码,所以编译器同时支持C和C++的语法,所以我没有使用Scanf和Printf方法,改用cout和cin的C++的库函数,另外,对于函数的参数方面,我尽量使用了C++支持的引用,而不是C的指针(C只支持指针),减少语法上的混淆.

好了,下面是2.2节-线性表的顺序实现的代码:

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

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

//建立Int型顺序型线性别
int const maxsize=10;
typedef 
struct
{
    
int data[maxsize];
    
int last;                //维护结点的个数,以1开始
}
sqlist;

//插入结点:value为插入的值,index是插入的索引但非数组的索引,error指向错误的提示
void insert_sqlist(sqlist & L,int value,int index,char * error)
{
    
if (L.last==maxsize)
    
{
        error
="溢出";
        
return;
    }

    
if (index<1 || index>L.last+1)
    
{
        error
="非法位置";
        
return;
    }

    
for(int j=L.last;j>=index;j--)
    
{
        L.data[j]
=L.data[j-1];
    }

    L.data[index
-1]=value;
    L.last
++;
}

//删除指定索引的结点 index为删除的索引
void delete_sqlist(sqlist & L,int index,char * error)
{
    
if (index<1 || index>L.last)
    
{
        error
="非法位置";
        
return;
    }

    
for(int j=index;j<L.last;j++)
    
{
        L.data[j
-1]=L.data[j];
    }

    L.last
--;
}

//定位
int locate_sqlist(sqlist & L,int value)
{
    
int i=1;
    
while(i<=L.last && L.data[i-1]!=value)
        i
++;
    
if (i<=L.last)
        
return i;
    
else
        
return 0;
}

//显示链表的内容
void display_sqlist(sqlist & L)
{
    
for(int i=0;i<L.last;i++)
    
{
        cout
<<""<<i+1<<"个结点的值为:"<<L.data[i]<<endl;
    }

}


int main(int argc, char* argv[])
{
    sqlist L;
    L.last
=0;
    
//
    cout<<"插入3个结点";
    
char * error=NULL;
    insert_sqlist(L,
1,1,error);
    insert_sqlist(L,
2,2,error);
    insert_sqlist(L,
3,2,error);
    display_sqlist(L);
    
//
    cout<<"删除第1个结点"<<endl;
    delete_sqlist(L,
1,error);
    display_sqlist(L);
    
//
    cout<<"查找值为2的元素位置为:"<<locate_sqlist(L,2)<<endl;

    
return 0;
}

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