数据结构经典案例教学文案

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

数据结构经典案例

1.停车场问题

停车场管理员的任务就是帮助车主把车停放在停车场中,或者是帮助车主将车开出乘车场。然后停车场中能够停放的车辆数目很多,这就使得让莫辆车开出停车场变得复杂。比如:要开走一辆车,则管理员需要把他前面的车全部暂时清除,然后等这辆车开出后再将这些车重新放入停车场。当然了,这个时候腾出了一个空位置,此位置由后面的车占据。

任务:编程模拟这样的情况,这里假设停车场最多可停放5辆车。data.txt记录了某一时间段内,该停车场车辆的到来与离开记录,刚开始,停车场是空的。其中大写字母A--P是车辆的代号,arrives--到来,departs---离开。

程序需要从data.txt中读取这些信息,并且用这些数据来模拟停车场的车辆调度情况。

data.txt内容如下:

A arrives

A departs

B arrives

C arrives

D arrives

C departs

E arrives

F arrives

G arrives

B departs

H arrives

D departs

E departs

I arrives

I departs

J arrives

F departs

K arrives

L arrives

M arrives

H departs

N arrives

J departs

K departs

O arrives

P arrives

P departs

O departs

L departs

实现代码如下:

模拟停车场问题.cpp(没有再继续分.h文件,混为一体了,主要.h文件过于简单)

[cpp]view plaincopyprint?

1.#ifndef CAR_H

2.#define CAR_H

3.#include

4.#include

ing namespace std;

6.class car

7.{

8.public:

9.car(string,int);

10.string getlicense();

11.int getmovedtimes();

12.~car();

13.void move();

14.private:

15.string license;//车的通行证

16.int movedtimes;//被移动的次数

17.};

18.#endif

19.car::car(string license,int movedtimes):license(license),movedtimes(0)

20.{

21.}

22.

23.string car::getlicense()

24.{

25.return license;

26.}

27.int car::getmovedtimes()

28.{

29.return movedtimes;

30.}

31.void car::move()

32.{

33.movedtimes++;

34.}

35.car::~car()

36.{}

37.

38.#include

39.#include

40.int main()

42.string in_filename="data.txt";//数据文件了,包含了停车场内的车辆进出

记录

43.ifstream inf(in_filename.c_str());//void open(const char* filename,int

mode,int access);另外,fstream还有和open()一样的构造函数,对于上例,在定义的时侯就可以打开文件了:

44.//fstream file1("c://config.sys");

45.

46.if(!inf)

47.{

48.cerr<<"文件打开失败!"<

49.return EXIT_FAILURE;

50.}

51.stack parking_lot,tempstack;//定义两个栈,一个模拟停车场,另

外一个用来暂时存放从停车场哪里暂时清除的车,当然最后还是得返回给停车场

52.car* pcar;

53.string license_plate,action;//分别记录从数据文件中读取的通行证跟行为

(到达?离开?)

54.//按行读取数据文件

55.while(!inf.eof())

56.{

57.inf>>license_plate>>action;

58.if(action=="arrives")//到达

59.{

60.if(parking_lot.size()<5)//栈不满的话,继续入栈

61.{

62.pcar=new car(license_plate,0);//这个就不用多罗嗦

63.parking_lot.push(pcar);

64.

65.}

66.else

67.

68.cout<<"抱歉"<

69.

70.}

71.else if(action=="departs")//如果是出发

72.{

73.//首先得给出判断,此时栈是否为空?而且出发的这辆车的

license_plate是否位于栈顶

74.while( (!parking_lot.empty()) && (parking_lot.top()-

>getlicense()!=license_plate))//while循环

相关文档
最新文档