C语言数据结构上机题

1.用单链表结构来存放26个英文字母组成的线性表(a,b,c…z),写出C语言程序
2.在1的基础上,随便在一个位置插入一个任意字母
好的会追加悬赏

#include "stdafx.h"
#include<iostream>
using namespace std;
typedef struct LNode
{
char data;
struct LNode * next;
}LNode,* LinkList;
void CreateList(LinkList &L)//创建链表存放26个字母组成的线性表
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
char c='z';
for(int i=26;i>0;i--)
{
LNode *p;
p=(LinkList)malloc(sizeof(LNode));
p->data=c--;
p->next=L->next;
L->next=p;
}
}
bool ListInsert(LinkList &L,int i,char c)//在第i个位置插入字母c
{
LNode * p=L;int j=0;
while(p&&j<i-1)
{
p=p->next;
++j;
}
if(!p||j>i-1)
return false;
LinkList s=(LinkList)malloc(sizeof(LNode));
s->data=c;
s->next=p->next;
p->next=s;
return true;
}
void main()
{
LinkList L;
CreateList(L);//1.创建链表存放26个字母组成的线性表
char c;int i;
cout<<"输入插入的字母"<<endl;
cin>>c;
cout<<"输入插入的位置(整数)"<<endl;
cin>>i;
if(ListInsert(L,i,c))//在第i个位置插入字母c
{
while(L->next!=NULL)//将插入后的线性表输出
{
cout<<L->next->data;
L=L->next;
}
}
}

//辛苦写完...刚调试通过...加分啊..
调试是在C++环境下调试的,如果你要在C环境下..把
cout<<L->next->data; 改为:
printf("%d",L->next->data);
cin>>c;改为:scanf("%c",c);
就ok了......

ps: o_o一般上机都是C++吧......
温馨提示:答案为网友推荐,仅供参考
第1个回答  2006-10-28
这个不是很难,我在写
你一定要加分啊~~

#include "malloc.h" /*也可能是这个#include <stdlib.h> */
#include "math.h"
#define null 0
#define len sizeof(struct ch)
struct ch{
char c;
struct ch *next;}

struct ch *link(void){
struct ch *head;
struct ch *p1,*p2;
int n=0;
p1=p2=(struct ch *)malloc(len);
scanf("%c",&p1->c);
head=null;
while(p->c!='#'){
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct ch*)malloc(len);
scanf("%c",&p1->c);
}
p2->next=null;
return(head);
}

void in(struct ch *head){
struct ch *p0,*p1,*p2;
p1=head;
p0=(struct ch*)malloc(len);
scanf("%c",&p0->c);
if(head==null){head=p0;p0->next=null;}
else {
p0->next=p1;
head=p0;}
}/*我就在表头上加一个*/
第2个回答  2006-10-29
#include<stdio.h>
#include<malloc.h>
PLNode CreateList()/*创建单链表*/
{PLNode P,head,q;
int i;
head=(PLNode)malloc(sizeof(LNode));
p=head;
p->next=NULL;
for(i=0;i<26;i++)
{q=(PLNode)malloc(sizeof(LNode));
q->character='a'+i;
q->next=NULL;
p->next=q;
p=q;
}
return PLNode;
}

voie Insert(PLNode head,int position,char chr)/*插入到第i的位置*/
{int i;
PNLode p,q;
if(Length(head)+1<position)
{printf("你要插入的位置不存在!");
exit(0);
}
else
{p=head;
i=0;
while(i<position-1)
{p=p->next;
i++;
}
q=(PLNode)malloc(sizeof(LNode));
q->character=chr;
q->next=p->next;
p->next=q;
}
}
main()
{PLNode head;
int i;
char ch;
head= CreateList();
printf("请输入你要插入的字符位置:");
scanf("%d",&i);
getchar();
printf("请输入你要插入的字符:");
ch=getchar();
Insert( head,i, ch);
}
相似回答