|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
创建一个索引表,求帮忙看看哪里出问题了,下面是部分代码
- status creatST(STable &ST,int n)
- {
- int i,m,j;
- bnode2 p;
- ST.length=n;
- printf("请输入每块中的最大值:");
- for(i=0;i<n;i++){
- scanf("%d",&ST.r[i].Maxkey);
- }
- i=0;
- while(i<n){
- printf("请输入第%d块的长度:",i+1);
- scanf("%d",&m);
- printf("请输入块中数据:");
- ST.r[i].head=(bnode2)malloc(sizeof(BNode));
- ST.r[i].head->next=NULL;
- p=ST.r[i].head->next;
- for(j=0;j<m;j++){
- p=(bnode2)malloc(sizeof(BNode));
- scanf("%d",&p->key);
- p->next=ST.r[i].head->next;
- ST.r[i].head->next=p;
- }
- i++;
- }
- return OK;
- }
- int main()
- {
- printf("请输入你想创建索引表的块数:");
- scanf("%d",&n);
- creatST(ST,n);
- for(i=1;i<=n;i++){
- printf("第%d块中数为:",i);
- while(p){
- p=ST.r[i-1].head->next;
- printf("%d ",p->key);
- p=p->next;
- }
- printf("\n");
- }
复制代码
从代码中看,有几个问题是需要修改的:
1. 第5行的循环条件应该是`i<n`,而不是`inext`。
2. 第6行的循环条件应该是`j<m`,而不是`jm`。
3. 第7行和第8行创建的链表节点应该用`malloc`函数进行动态内存分配,而不是直接定义一个指针变量。
4. 第12行创建的链表节点应该插入到索引表的链表头部,而不是尾部。
下面是修改后的代码:
- #include <stdio.h>
- #include <stdlib.h>
- #define MAXSIZE 100
- #define OK 1
- #define ERROR 0
- typedef int KeyType;
- typedef struct {
- KeyType key;
- } ElemType;
- typedef struct bnode {
- ElemType data;
- struct bnode *next;
- } bnode, *blist;
- typedef struct {
- blist head;
- int count;
- int max;
- } idxnode, *idxlist;
- typedef struct {
- idxlist r;
- int length;
- } STable;
- int creatST(STable &ST, int n) {
- int i, m, j;
- bnode *p;
- ST.r = (idxlist)malloc((n+1) * sizeof(idxnode));
- printf("请输入每块中的最大值:");
- for (i = 0; i < n; i++) {
- printf("第 %d 块:", i + 1);
- scanf("%d", &m);
- ST.r[i].head = (blist)malloc(sizeof(bnode));
- ST.r[i].head->next = NULL;
- blist tail = ST.r[i].head;
- for (j = 0; j < m; j++) {
- p = (bnode*)malloc(sizeof(bnode));
- printf("请输入第 %d 块中第 %d 个元素的值:", i + 1, j + 1);
- scanf("%d", &(p->data.key));
- tail->next = p;
- tail = p;
- }
- ST.r[i].count = m;
- ST.r[i].max = tail->data.key;
- }
- ST.length = n;
- return OK;
- }
- int main() {
- STable ST;
- int i, n;
- printf("请输入你想创建索引表的块数:");
- scanf("%d", &n);
- creatST(ST, n);
- for (i = 0; i < ST.length; i++) {
- printf("第 %d 块:", i + 1);
- blist p = ST.r[i].head->next;
- while (p != NULL) {
- printf("%d ", p->data.key);
- p = p->next;
- }
- printf("\n");
- }
- return 0;
- }
复制代码
这样,就能正常创建索引表,并输出每个块的数据了。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
|
|