永发信息网

帮我写段C程序实例!

答案:3  悬赏:20  手机版
解决时间 2021-06-04 01:41
  • 提问者网友:呐年旧曙光
  • 2021-06-03 10:48

要求:用结构体 用链表,实现结构体之间的添加。删除!

简单的就行!比如结构体里有姓名 分数!

今天看了两节课的链表!最终还是无法掌握!

最佳答案
  • 五星知识达人网友:未来江山和你
  • 2021-06-03 10:56

#include<iostream>
using namespace std;
struct link
{
int data;
link *next;
};
link *hcreat()
{
int i;
link *p,*s;
p=new link;
p->next=NULL;
cout<<"输入数据:";
cin>>i;
while(i)
{
s=new link;
s->data=i;
s->next=p->next;
p->next=s;
cout<<"输入数据:";
cin>>i;
};
return p;
}
link *Locate(link *head,int x)
{
link *p;
p=head->next;
while((p!=NULL)&&(p->data!=x))
{
p=p->next;
}
return p;
}
void insert(link *head,int x,int y)
{
link *p,*s;
s=new link;
s->data=x;
if(head->next==NULL)
{
head->next=s;
s->next=NULL;
}
p=Locate(head,y);
if(p==NULL)
cout<<"error";
else
{
s->next=p->next;
p->next=s;
}
}
void Delete(link *head,int x)
{
link *p,*s;
s=head;
p=head->next;
while((p!=NULL)&&(p->data!=x))
{
s=p;
p=p->next;
}
if(p==NULL)
cout<<"error";
else
{
s->next=p->next;
delete(p);
}
}
void print(link *head)
{
link *p;
p=head->next;
while(p!=NULL)
{
cout<<p->data<<"-";
p=p->next;
}
cout<<endl;
}
int main()
{
link *H;
int k;
int x,y;
do
{
cout<<"\n\n\n\n";
cout<<"\t\t\t链表子系统\n";
cout<<"\t\t***************************\n";
cout<<"\t\t** 1.建 表 **\n";
cout<<"\t\t** 2.插 入 **\n";
cout<<"\t\t** 3.删 除 **\n";
cout<<"\t\t** 4.查 找 **\n";
cout<<"\t\t** 5.显 示 **\n";
cout<<"\t\t** 0.返 回 **\n";
cout<<"\t\t***************************\n";
cout<<"\t\t请输入0-5项:\n";
cin>>k;
switch(k)
{
case 1:
H=hcreat();
break;
case 2:
cout<<"\n请输入插入位置的数值y:";
cin>>y;
cout<<"\n请输入要插入的数据x:";
cin>>x;
insert(H,x,y);
cout<<"插入后链表为:";
print(H);
break;
case 3:
cout<<"\n请输入要删除的元素x:";
cin>>x;
Delete(H,x);
cout<<"删除后链表为:";
print(H);
break;
case 4:
cout<<"\n请输入要查找的数值x:";
cin>>x;
link *p;
p=Locate(H,x);
if(p!=NULL)
{
print(H);
cout<<"值为x所在的位置是"<<p;
}
else
cout<<"链表中无此无素!";
break;

case 5:
cout<<"\n输出线性表:";
print(H);
break;
}
}while(k!=0);
}



这是我学习后写的,可能有些出入。希望能帮助你,

全部回答
  • 1楼网友:妄饮晩冬酒
  • 2021-06-03 11:57
写了个超简单的,节点里只包含一个元素(当然这无关紧要,你可以自己扩充),包括了在特定节点插入和删除特定节点的2个操作: #include <stdio.h> #include <stdlib.h> typedef struct _slist { int data; struct _slist* next; } *node, slist; node insert(node* head, node p, int data) { node n; n = (node)malloc(sizeof(slist)); n->data = data; n->next = p ? p->next : *head; (p ? p->next : *head) = n; return n; } node create(int* beg, int* end) { node head, t; head = t = NULL; while(beg != end) t = insert(&head, t, *beg++); return head; } void remove(node* head, node r) { node prev; if(r == *head) { *head = r->next; } else { prev = *head; while(prev->next != r) prev = prev->next; prev->next = r->next; } free(r); } void print(node head) { while(head) { printf("%d ", head->data); head = head->next; } putchar('\n'); } int main() { int a[] = {1,2,3,4,5}; node head = create(a, a + 5); print(head); remove(&head, head->next); print(head); getchar(); return 0; }
  • 2楼网友:怙棘
  • 2021-06-03 11:08
用C还是C++
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯