我的创建链表的代码有什么问题? [英] What is wrong in my code of creating linked list?

查看:55
本文介绍了我的创建链表的代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int n;
    struct node *next;
};
int main()
{
    int n;
    struct node *head, *newnode;
    newnode = (struct node *)(malloc(sizeof(struct node)));
    head=NULL;
    printf("blah");
    while(1);
    {
        printf("enter the character:(1/0)\n");
        scanf("%d",&newnode->n);
        if(n==0)
        {
            return 0; 
        }
            else
            {
                newnode=head;
                newnode->next=NULL;
            }
     }
     return 0;

}





我的尝试:



我试图创建单链表。



What I have tried:

I was trying to create single linked list.

推荐答案

您正在分配 NULL newnode 然后访问它:

You are assigning NULL to newnode and accessing it then:
head=NULL;
// head is not changed anymore later

// Here newnode is set to NULL because head is NULL
newnode=head;
// Here you get an access violation
newnode->next=NULL;





你应该阅读关于链接列表的教程,如链接列表 - 学习C - 免费交互式C教程 [ ^ ]。


你应该学会使用调试器尽快。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候您接近一个错误。



建议:

拿一张纸,记下添加或删除时附加的内容列表中的项目,让你的程序做同样的事情。使用调试器检查程序是否正确。
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

Advice:
Take a sheet of paper and note what append when you add or remove an item in the list and make you program do the same. Use the debugger to check that the program is right.


这篇关于我的创建链表的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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