求教 ,关于链表的。。
没学过数据结构,老师突然要我们弄个用链表做的作业 大概就是创建链表记录学生的各项信息 输入年龄就可以删除对应年龄的结点, 我自己看数据结构的书架上百度 弄了个东西出来,但有7个致命错误。。。。求教各位大神啦谢谢了 (为了简单没加可以删除多个结点)这是我的代码
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
using namespace std;
struct Node{
int num;/*学号*/
string name; /*学生姓名*/
int sex; /*学生性别:男1 女0*/
int age; /*学生年龄*/
struct Node* next; /*指针域*/
};
Node *head,*p1,*p2,*p,*q;
int count;
Node* creat() /*创建链表函数定义*/
{
int n=0;
p1=new Node;
cin>>p1->num;
cin>>p1->name;
cin>>p1->sex;
cin>>p1->age;
head=NULL;
while(p1->num!=0)
{if(n==0)
{head=p1;
}else
p2->next=p1;
p2=p1;
p1=new Node;
cin>>p1->num;
cin>>p1->name;
cin>>p1->sex;
cin>>p1->age;
n++;
}
p2->next=NULL;
return head;
};
void print() /*遍历显示函数*/
{ p=head;
while(p!=NULL)
{cout<<"学号"<<p->num<<"姓名"<<p->name<<"性别"<<p->sex<<"年龄"<<P->age<<endl;
p=p->next;
}
};
int Find(int a) /*按值查找结点函数*/
{p=head;count=1;
while(p!=NULL)
{if(p->age==a)return count;
p=p->next;
count++;
}
return 0;
}
void Delete(int i) /*删除结点函数*/
{if(i==1)
delete head;
else{
p=head;count=1;
while(p!=NULL&&count<i-1)
{p=p->next;
count++;
}
if(p==NULL||p->next==NULL)
throw "位置";
else{
q=p->next;
p->next=q->next;
delete q;
}
}
int main(){
cout<<"请按顺序输入学号,姓名,性别,年龄"<<endl;
creat();
print();
cout<<"请输入要删除学生的年龄"<<endl;
cin>>a;
Delete(Find(a));
return 0;
};我没用VS2010用的VC6.0
[解决办法]
最好把错误也给出来,在哪行出的错误
[解决办法]
我猜是不是因为cin之后的回车没接收啊?
[解决办法]
其实你可以使用VS单步一下,就可以看出错误了,对你的学习也有帮助
我恨我那时候的作用就是这样找人帮忙的,所以一直是个菜鸟!
[解决办法]
你的错误好多,这个是可以直接运行的代码:
- C/C++ code
include <iostream>#include <string>using std::cout;using std::string;using std::cin;using std::endl;struct node{int num;string name;string sex;int age;node *next;};void createnode(node * &head){ node *p,*q=head; int num; while(true) { cout <<"please input num:"; cin>>num; if(num == 0) break; p=new node; p->next=NULL; p->num = num; cout <<"input name:"; cin >> p->name; cout <<"input sex:"; cin>>p->sex; cout << "input age:"; cin>>p->age; q->next=p; q=p; }}void print(node *head){ if(head->next) cout<<"学号\t姓名\t性别\t年龄\t"<< endl; else cout <<"Information is empty!"; while(head->next) { cout<<head->next->num<<"\t"<<head->next->name<<"\t"<<head->next->sex<<"\t"<<head->next->age<<"\t"<<endl; head=head->next; }}node * findnode(node *head,int age){ while(head->next) { if(age == head->next->age) break; head=head->next; } return head->next;}bool deletenode(node *head,node *p){ if(p) { while(head->next != p) head=head->next; head->next=p->next; delete p; return true; } else return false;}void test5node(){ node *head = new node; node *p; head->next=NULL; createnode(head); print(head); int age; cout <<"please input age that you want to delete:"; cin >>age; p = findnode(head,age); if(deletenode(head,p)) cout <<"成功删除!"<< endl; else cout <<"删除失败或则不存在该年龄的同学!"<< endl; print(head);}