简单的链表-C [英] Simple linked list-C

查看:141
本文介绍了简单的链表-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从C编程服用暑假下来后,我回到了它的厚上课,我试图追赶,尤其是在三分球。

After taking the summer off from C programming, I'm back in the thick of it for classes and am trying to catch up, particularly in pointers.

目前的任务已经让我们从一个数组结构转换程序,以一个简单的链表。为了刷新我的记忆中,我试着在一个独立的程序实现它,但我遇到了麻烦。

The current assignment has us converting a program from an array structure to a simple linked list. In order to refresh my memory, I've tried implementing it in a standalone program, but am running into trouble.

我的code:

struct node{
  int val;
  struct node *next;
};

typedef struct node *item;

item newNode(void); //function prototype

void main(){
    item *cur, *itemList;
    int i;

    itemList=NULL;

    for (i=0; i<=10; i++){
        cur= newNode();
        cur->val=i;
        cur->next= itemList;

    }
}

item newNode(void) {
    item box;  /* the new object to return */

    box = (item) malloc (sizeof (struct node));

    if (box == NULL) {
        printf("ERROR: emalloc failed for new Box\n");
        exit(0);
    }

    /* initialize fields */
    box->val=0;

    return box;

}

第一条错误消息是在 CUR = newBox()来,并指出不兼容的指针类型的赋值是正在取得进展。我不知道为什么,因为恶狗是一个指向一个节点,框的结构。在什么地方不兼容的指针来的?

The first error message is coming at cur= newBox() and is stating that an assigment from an incompatible pointer type is being made. I'm not sure why, since cur is a pointer to a node, and box is a structure. Where does the incompatible pointer come from?

推荐答案

第一个问题是,你做的项目* CUR,* ITEMLIST; 这是一个节点** 。更改为项目CUR,ITEMLIST; 获得节点* 的;你并不需要一个指针指向一个节点,只是一个指针节点

The first problem is that your doing item *cur, *itemList; which is a node**. Change that to item cur, itemList; to get node*'s; you don't need a pointer to a pointer to a node, just a pointer to a node.

另一个问题是,你的节点的所有接下来指针设置为 ITEMLIST 没有设定 ITEMLIST CUR 在每个循环迭代结束(这会让 ITEMLIST 指向列表的开头在循环结束时)。

Another problem is that you're setting all the next pointers of your nodes to itemList without setting itemList to cur at the end of each loop iteration (which will make itemList point to the beginning of the list at the end of the loop).

这篇关于简单的链表-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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