C问题-无法计算如何将指针分配给列表的开头 [英] C issue - Can't figure how to assign pointer to beginning of list

查看:78
本文介绍了C问题-无法计算如何将指针分配给列表的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的任务,教授要我们做. 基本上是从文本文件中提取一些数字并加载到链接列表中. 我不想深入了解细节,但是我有一个基本问题.

I have a simple assignment that the professor wants us to do. Basically to pull in some numbers from a text file and load into a linked list. I don't want to get to much into the details but I have a basic question.

他为我们提供了如下功能:

He provided us with a function like so:

INTLIST* init_intlist( int n ) 
{
INTLIST *lst;
lst = (INTLIST *)malloc(sizeof(INTLIST));
lst->datum = n;
lst->next = NULL;
return lst;
}

此函数用于初始化具有第一个元素的链表.然后他要求我们用此签名定义一个函数:

This function is used to initialize the linked list with the first element. Then he asked us to define a function with this signature:

int insert_intlist( INTLIST *lst, int n )

所以我想他只是想让我们添加到链接列表中,所以我尝试了这一点:

So I assume he just wants us to add to the linked list so I tried this:

int insert_intlist( INTLIST *lst, int n )
 {
 INTLIST* lstTemp;
 lstTemp = (INTLIST *)malloc(sizeof(INTLIST));
 lstTemp->datum = n;
 lstTemp->next = lst;
 lst = lstTemp;       
 free(lstTemp);          
 }

所以我的想法是,它创建一个临时节点,分配数据值(基准),并分配下一个指针以指向当前指针所指向的位置.然后,我将主指针重新分配给这个新创建的临时节点.

So what my thought process was is that it creates a temporary node, assigns the data value (Datum) and assigns the next pointer to point to where the current pointer is pointing at. Then I reassign the main pointer to this newly created temp node.

这样,我们有2个节点:

That way we have for instance 2 nodes:

[新临时节点]-> [上一个初始化节点]

[New Temp Node] -> [Prev Initialized Node]

当我逐步执行代码时,它看起来很棒...

When I step through the code it looks great...

然后回到主菜单,我只有一个功能可以打印列表:

Then back in main I have just a function to print the list:

                   while (lst!=NULL)
                      {
                       printf("The value is:%d", lst->datum);
                       lst=lst->next;
                      }

问题是这似乎只显示一位数字(即我从文件中读取的第一位数字,我认为这是列表中的最后一位,或者至少我认为这是列表中的最后一位) ).

The problem is this only seems to print one digit (namely the first digit that I am reading in from the file, which I think is the last one in the list or at least I thought it was the last one in the list).

但是应该继续进行,因为我的文件中有10位数字.我知道代码很脏,我会清理它……如果有人需要更多信息,这是我的整个主要功能:

But it should keep going through as I have 10 digits in the file. I know the code is very dirty and I will clean it up...here is my entire main function if anyone needs more info:

#include <stdio.h>
#include <stdlib.h>
#include "intlist.h"

int main(int argc, char *argv[])
{
  char c;    /* Character read from the file. */
  FILE* ptr;   /* Pointer to the file. FILE is a
       structure  defined in <stdio.h> */
  int index=0;
  //INTLIST* aList[10]; //will use later

    /* Open the file - no error checking done */
  ptr = fopen("1.txt","r");
    /* Read one character at a time, checking 
       for the End of File. EOF is defined 
      in <stdio.h>  as -1    */

  if(ptr==NULL) {
    printf("Error: can't open file.\n");
    /* fclose(file); DON'T PASS A NULL POINTER TO fclose !! */
    return 1;
  }

  //aList[index] = malloc(sizeof(INTLIST)); WE NEED THIS LATER ON....
  INTLIST *lst=NULL;

  while ((c = fgetc(ptr)) != EOF)
  {
        if (c != ' ') 
        {
         //make sure it isnt a space
         int i = c - '0'; //get the value from the text file
             if(c=='\n') 
                 {
                      // aList[index]=lst;
                      // index++;
                      // aList[index] = malloc(sizeof(INTLIST));

                           while (lst!=NULL)
                              {
                               printf("The value is:%d", lst->datum);
                               lst=lst->next;
                              }

                           free(lst);
                           free(aList[index]);
                           return 0;
                          //new line in the file 
                         //create another linked list
                 }

            if (lst==NULL)
             lst = init_intlist(i);
            else
             insert_intlist( lst, i); 
        }
  }

  fclose(ptr);
  system("PAUSE"); 
  return 0;
}

这里是intlist.h,适合可能需要它的任何人:

Here is intlist.h for anyone who may need it:

#ifndef __intlist_h__
#define __intlist_h__
/* each entry in the list contains an int */
typedef struct intlist {
int datum;
struct intlist *next;
} INTLIST;
INTLIST *init_intlist( int n ); /* initializes the intlist with initial datum n */
int insert_intlist( INTLIST *lst, int n ); /* Inserts an int (n) into an intlist from the beginning*/
void list_append(INTLIST *list, void *datum); /* Inserts entry to the end of the list */
INTLIST* list_front(INTLIST *list); /*return the element at the front of the list, and remove it 
from the list*/
void list_map( INTLIST *list, void (*f)(void *) ); /*Applies a function to each element of the list */
void list_delete( INTLIST *list ); /* Deletes (and frees) all entries in the list */
#endif

推荐答案

此处有两个问题.

我将从一个错误开始:

int insert_intlist( INTLIST *lst, int n )
 {
 INTLIST* lstTemp;
 lstTemp = (INTLIST *)malloc(sizeof(INTLIST));
 lstTemp->datum = n;
 lstTemp->next = lst;
 lst = lstTemp;       
 free(lstTemp);             //   <<<<<  NO!
 }

您仍在使用该内存,因此无法释放它.

You are still using that memory, so you can't free it.

第二,提供给您的用于插入的原型无法返回列表的新开头,因此您无法更改列表的开头.这意味着您必须将新节点添加到,而不是像前面那样将新节点添加到前节点.

Secondly, the proto-type supplied to you for insertion has no way to return a new front of the list, so you can not change the front of the list. This implies that you must add new nodes to the back, rather than to the front as you have done.

此外,提供的返回类型int可能意味着他期望列表中的节点数为零,这没问题,因为无论如何您都必须走遍列表以查找后方.

Also, the supplied return type of int probably means that he expects out the number of nodes in the list, which is no problem as you're going to have to walk the list to find the back anyway.

还有另一个要解决的问题,您一点也不坏.

Have another go at it, you're not doing badly at all.

这篇关于C问题-无法计算如何将指针分配给列表的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆