Tauruser

Enjoy Every Day
posts - 34, comments - 95, trackbacks - 0, articles - 5
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

算法与数据结构实验(一)

Posted on 2006-03-04 13:14 Tauruser 阅读(470) 评论(0)  编辑 收藏 引用 所属分类: 算法与数据结构
题目:
       1、试编写在数组中插入一个元素和删除一个元素的函数,并调用此函数作一个整型数组的插入和删除,要求整形数组开始含有10个元素,插入的位置可在任意两个数组元素之间、第一个元素前和最后一个元素后,删除任意指定位置的元素,并将各元素的位置及相应的元素值打印出来。

      正如《我的算法与数据结构学习(二) 》中谈到,在顺序存储中,插入与删除操作的实现其关键在于对顺序存储空间的管理。作为顺序存储,较为典型的是在数组中进行。当进行插入和删除操作时,都要涉及到各个数组元素的移位,移位的顺序是关键的,一不小心搞错了移位的顺序就可能导致数组元素内容的丢失。
 1#include <iostream>
 2using namespace std;
 3int a[20];
 4int count;
 5int choice;
 6bool Exit(0);
 7void insert(int *line);
 8void del(int *line);
 9void display(int *line);
10
11
12int _tmain(int argc, _TCHAR* argv[])
13{
14    for(int i(0);i<10;i++)
15        a[i]=i;
16    count=10;
17    while(!Exit)
18    {
19        cout<<"1.insert a num"<<endl;
20        cout<<"2.delete a num"<<endl;
21        cout<<"3.dispaly the list"<<endl;
22        cout<<"0.exit"<<endl;
23        cout<<"please input your choice:";
24        cin>>choice;
25        if(choice==1)
26        {
27            insert(a);
28        }

29        else if(choice ==2)
30        {
31            del(a);
32        }

33        else if(choice==3)
34        {
35            display(a);
36        }

37        else if(choice==0)
38        {
39            Exit=true;
40        }

41    }

42    cout<<"Power by Tauruser";
43    return 0;
44
45}

46
47void insert(int *line)
48{
49    int loc,num;
50    cout<<"where you would like to insert:";
51    cin>>loc;
52    if(loc<1 || loc>count+1)
53    {
54        cout<<"data overflow";
55        return;
56    }

57    cout<<"what num you would like to insert:";
58    cin>>num;
59    for(int i=count;i>loc-1;i--)
60    {
61        line[i]=line[i-1];
62    }

63    count++;
64    line[loc-1]=num;
65}

66
67void del(int *line)
68{
69    int loc;
70    cout<<"which num you would like to delete:";
71    cin>>loc;
72    if(loc<1 || loc>count)
73    {
74        cout<<"data overflow";
75        return;
76    }

77    for(int i=loc-1;i<count-1;i++)
78    {
79        line[i]=line[i+1];
80    }

81    count--;
82}

83
84void display(int *line)
85{
86    for(int i(0);i<count;i++)
87    {
88        cout<<"No."<<i+1<<" num is "<<line[i]<<endl;
89    }

90}

91
      从insert()与del()两个函数来看,在数组里进行移位的顺序刚才相反。插入从后到前,删除从前到后。这样的顺序确保了,元素值不会给覆盖丢失。其实如果再提供一个temp的变量,也可以实现移动顺序的改变。但就要再引入一个变量了。

PS:另外说一点,有同学问我为什么在VS.net平台里老是没有办法#include <iostream.h>。我想可能VS.net已经在C++中放弃支持这个了。可以换成
#include <iostream>
using namespace std;
使用ISO C++的库就行了。不知道我的见解是否正确。

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理