6-2 工作备忘录的生成(链表)
作者 何振峰
单位 福州大学
每天都要处理很多事务,为了更好地安排工作,希望在每天开始工作前,根据工作记录,生成工作备忘录。首先输入工作记录数(大于0的一个整数),再逐条输入各条工作记录,每条工作记录包括:工作名,开始时间,结束时间。假设每项工作的开始时间均小于它的结束时间,并且各项工作的开始时间互不相同。
我们的工作是需要把这些工作记录按开始时间排序并输出,在输出时,如果某项工作与若干项工作冲突(在做该项工作时,需要同时做其它工作),则在该工作名前加’*'。
函数接口定义:
Node* add(Node *, Node *);
void display(Node *);
裁判测试程序样例:
#include<iostream>
#include <string>
using namespace std;
struct Node{
string name;
int start;
int end;
Node *next;
};
Node* add(Node *, Node *);
void display(Node *);
bool check(Node *head)
{
if(head==NULL || head->next==NULL) return true;
Node *p=head->next;
if(head->start > p->start) return false;
return check(p);
}
int main()
{
Node *head=NULL, *p;
int i, repeat;
cin>>repeat;
for(i=0;i<repeat;i++){
p = new Node;
cin>>p->name>>p->start>>p->end;
p->next=NULL;
head = add(head, p);
}
if(!check(head)) cout<<"ERROR"<<endl;
display(head);
return 0;
}
/* 请在这里填写答案 */
输入样例:
4
aaa 19 20
ccc 169 200
ddd 153 170
bbb 20 111
输出样例:
aaa 19 20
bbb 20 111
*ddd 153 170
*ccc 169 200
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
代码
Node *add(Node *head, Node *p)
{
if (head == NULL)
return p;
if (head->start > p->start) // 如果P应该是第一个
{
p->next = head;
return p;
}
else if (head->next == NULL) // 如果p是第二个
{
head->next = p;
return head;
}
Node *tempNode = head->next; // 开始比较
Node *preNode = head; // 比较的前一个节点
while (tempNode)
{
if (tempNode->start < p->start)
{
// 如果p要为最后一个文件
if (tempNode->next == NULL)
{
tempNode->next = p;
return head;
}
preNode = tempNode;
tempNode = tempNode->next;
}
else
{
preNode->next = p;
p->next = tempNode;
return head;
}
}
}
bool ifCollide(Node *head, Node *p)
{
Node *tempNode = head;
while (tempNode)
{
if (tempNode->name == p->name)
{
tempNode = tempNode->next;
continue;
}
if (tempNode->start > p->start && tempNode->start < p->end)
return true;
if (tempNode->end > p->start && tempNode->end < p->end)
return true;
// 开始忽略了下面两个情况
if (p->end > tempNode->start && p->end < tempNode->end)
return true;
if (p->start > tempNode->start && p->start < tempNode->end)
return true;
tempNode = tempNode->next;
}
delete tempNode;
return false;
}
void display(Node *head)
{
Node *p = head;
while (p)
{
cout << (ifCollide(head, p) ? "*" : "") << p->name << " " << p->start << " " << p->end << "\n";
p = p->next;
}
delete p;
}
- 当使用指针的时候,要考虑到指针为空的情况,否则就很容易出现段错误。
- 发生冲突总共有四种情况,不能遗漏。

4192

被折叠的 条评论
为什么被折叠?



