題目:
1、試編寫在數組中插入一個元素和刪除一個元素的函數,并調用此函數作一個整型數組的插入和刪除,要求整形數組開始含有10個元素,插入的位置可在任意兩個數組元素之間、第一個元素前和最后一個元素后,刪除任意指定位置的元素,并將各元素的位置及相應的元素值打印出來。
正如《我的算法與數據結構學習(二) 》中談到,在順序存儲中,插入與刪除操作的實現其關鍵在于對順序存儲空間的管理。作為順序存儲,較為典型的是在數組中進行。當進行插入和刪除操作時,都要涉及到各個數組元素的移位,移位的順序是關鍵的,一不小心搞錯了移位的順序就可能導致數組元素內容的丟失。
PS:另外說一點,有同學問我為什么在VS.net平臺里老是沒有辦法#include <iostream.h>。我想可能VS.net已經在C++中放棄支持這個了。可以換成
#include <iostream>
using namespace std;使用ISO C++的庫就行了。不知道我的見解是否正確。
1、試編寫在數組中插入一個元素和刪除一個元素的函數,并調用此函數作一個整型數組的插入和刪除,要求整形數組開始含有10個元素,插入的位置可在任意兩個數組元素之間、第一個元素前和最后一個元素后,刪除任意指定位置的元素,并將各元素的位置及相應的元素值打印出來。
正如《我的算法與數據結構學習(二) 》中談到,在順序存儲中,插入與刪除操作的實現其關鍵在于對順序存儲空間的管理。作為順序存儲,較為典型的是在數組中進行。當進行插入和刪除操作時,都要涉及到各個數組元素的移位,移位的順序是關鍵的,一不小心搞錯了移位的順序就可能導致數組元素內容的丟失。
1
#include <iostream>
2
using namespace std;
3
int a[20];
4
int count;
5
int choice;
6
bool Exit(0);
7
void insert(int *line);
8
void del(int *line);
9
void display(int *line);
10
11
12
int _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
47
void 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
67
void 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
84
void 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的變量,也可以實現移動順序的改變。但就要再引入一個變量了。
2

3

4

5

6

7

8

9

10

11

12

13



14

15

16

17

18



19

20

21

22

23

24

25

26



27

28

29

30



31

32

33

34



35

36

37

38



39

40

41

42

43

44

45

46

47

48



49

50

51

52

53



54

55

56

57

58

59

60



61

62

63

64

65

66

67

68



69

70

71

72

73



74

75

76

77

78



79

80

81

82

83

84

85



86

87



88

89

90

91

PS:另外說一點,有同學問我為什么在VS.net平臺里老是沒有辦法#include <iostream.h>。我想可能VS.net已經在C++中放棄支持這個了。可以換成

