如何在以下链表程序中停止无限迭代? [英] How do I stop the infinite iteration occuring in the following linked list program ?

查看:68
本文介绍了如何在以下链表程序中停止无限迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我创建的代码,用于创建和打印c.I输入的数据从1到5,当它开始打印数字时,它继续打印5直到我以某种方式终止程序。编写代码中可能出现的错误是什么?

Here is the code i created to create and print a linked list in c.I entered data from 1 to 5 and when it starts to print the numbers, it keeps on printing 5 until i terminate the program somehow. What could be the possible error in the written code ?

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
 	 int data;
 	 struct node *link;
}list;
void createList(){
	 list *start=NULL;
	 char ch;
     do{
		 list *ptr, *cpt;
		 ptr=(list*)malloc(sizeof(list));
		 printf("Enter data\n");
		 scanf("%d",&ptr->data);
		 ptr->link=NULL;
         if(start==NULL){
			 start=ptr;
			 cpt=ptr;
		   }
		 else{
			 cpt->link=ptr;
			 cpt=ptr;
		 }
         printf("Do you want more : ");
		 ch=getche();
		 printf("\n");
	  }while(ch!='n');
 }
void traverseNode(){
	  list *ptr, *start;
	  ptr=start;
	  while(ptr!=NULL){
		  printf("%d ",ptr->data);
		  ptr->link=ptr;
		}
  }
void main(){
	 createList();
	 traverseNode();
   }





我的尝试:



我试图修改函数并将代码放在main中但仍然没有结果。

尝试使函数成为int类型但仍然被卡住了。



What I have tried:

I have tried to modify the function and put the code in main but still no result.
Tried to make the functions int type but still got stucked.

推荐答案

引用:

当它开始打印数字时,它会继续打印5

when it starts to print the numbers, it keeps on printing 5



link 5是否有可能指向自己的节点?

使用调试器跟踪你的程序正在做。



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



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

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

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



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


Is it possible that link of 5 is pointing its own node ?
Use the debugger to track what your program is doing.

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.


这篇关于如何在以下链表程序中停止无限迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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