没有为SLL编写c程序

时间:2016-02-25 06:52:13

标签: c

问:请帮我这个程序不能正常工作。   不显示值。这个程序是我试图在c上运行的单链表的一个例子。     `

#include<stdio.h>
 #include<stdlib.h>        //malloc defined
struct node       
{
       int data;
       struct node *next;      
       };
 add()      //add function
  {
      int value;
       struct node *n;
       n=(struct node*)malloc(sizeof(struct node));  //mem allocation
       printf("enter the value to add\n");
       scanf("%d",&value);
       n->data=value;
       n->next=NULL;
      // n=n->next;
      // n->next=NULL;
       }  
  delete()     //delete function
  {
       //   n=n->next;
          struct node *n;    //declaration
          printf("the node deleted is %d",n->data);
          free(n);
          }

  display()          //display function
  {
           struct node *n;
           while(n!=NULL)
             {
             printf("%d",n->data);
             n=n->next;

             }
           }             
int main()
{
     int ch;
     while(1)
     {
             printf("do you want to add node press 1\n");

             printf("do you want to delete node press 2\n");

             printf("do you want to display node press 3\n");

             printf("do you want to exit press 4\n");
             scanf("%d",&ch);
     switch(ch)
     {
        case 1:add();
               break;

        case 2:delete();
               break;

        case 3:display();
               break;

        case 4:exit(0);


        default: printf("wrong choice!!!\n");                                      

     }
     }
     return 0;
     getch();
     }
 please help me this program is not working properly.

没有显示值。这个程序是我试图在c上运行的单链表的一个例子。

3 个答案:

答案 0 :(得分:0)

printf("%d",n->data);未打印,因为:

struct node *n;  // n is not determined.
while(n != NULL) // undefined behaviour

nn函数中的其他add()不同。您从未将结构传递给其他函数,因此它不会执行您希望它执行的操作。

答案 1 :(得分:0)

  1. 在函数display()中,局部变量&#39; n&#39;只是声明但没有定义,所以这里&#39; n&#39;只是一个狂野的指针。它也发生在函数delete()中。
  2. 它不是实现单个链表的正确方法。在函数add()中,您编写的只是创建节点,而不是将节点添加到链表。

答案 2 :(得分:0)

cSplit function