打印链表中链接的值

时间:2011-08-02 13:28:13

标签: c

我在C中编写了一个链接列表程序。但我打印链表的代码显示错误。我无法理解出了什么问题。任何人都可以帮我找出我的代码中出错的地方

#include<stdio.h>
#include<stdlib.h>
struct node{
  int link_data;
  struct node *next;
};
void add_node(struct node *,int);
int delete_node(struct node *);
struct node *front = NULL,*rear = NULL;
int main(){
  struct node *l = (struct node *)malloc(sizeof(struct node *));
  struct node *inc = (struct node *)malloc(sizeof(struct node *));
  int number,i,option,del_node;
  while(1){
    printf("Enter the option:\n1. Add node\n2. Delete node\n");
    scanf("%d",&option);
    switch(option){
      case 1:
        printf("Enter the number to be add\n");
        scanf("%d",&number);
        add_node(l,number);
        break;
      case 2:
        del_node = delete_node(l);
        printf("%d has been removed\n",del_node);
        break;
      case 3:
        for(inc = front ; inc < rear ; inc = inc->next){
          print("%d",inc->link_data);   <<<<<<<<<<<<<<<<< Error part of the program
        }
        break;
      case 4: 
        exit(0);
        break;
    }
  }
}
void add_node(struct node *l,int number){
  struct node *newnode = (struct node *)malloc(sizeof(struct node *));
  if(front == NULL){
    newnode->link_data = number;
    newnode->next = NULL;
    front = newnode;
    l = newnode;    
  }
  else{
    newnode->link_data = number;
    l -> next = newnode;
    l = newnode;
  }
}
int delete_node(struct node *l){
  int node_del;
  struct node *inc;
  for(inc = front ; inc < l ;inc = inc -> next );
  node_del = inc->link_data;
  l = inc;
  l -> next = NULL;
  return node_del; 
}

2 个答案:

答案 0 :(得分:3)

$ gcc -o ll -Wall -g -O0 ll.c
ll.c: In function ‘main’:
ll.c:29:11: warning: implicit declaration of function ‘print’ [-Wimplicit-function-declaration]
ll.c:13:14: warning: unused variable ‘i’ [-Wunused-variable]

您想使用printf,而不是print。 还有一个名为i的变量,你不使用它。

在实际打印位上,您永远不会指定rear。您可能也不想使用测试inc < rear;通常链接列表在其next指针为NULL时结束。

add_node中,您将front指向新节点。你可能并不是故意这样做。

答案 1 :(得分:2)

好吧,incread是指针。所以inc < read没有多大意义(比较那样的地址没用)。你可以尝试:

for (inc = front; inc != rear; inc = inc->next)