C语言 链接列表打印问题:

hfyxw5xn  于 2023-08-03  发布在  其他
关注(0)|答案(1)|浏览(113)
#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
      int value;
      struct Node *next;
}Node;

Node *create_node(int value){
  Node *p=malloc(sizeof(Node));
  p->value=value;
  p->next=NULL;
  return p;
}

void *insert_at_head(Node **head,Node *node){
  node->next=*head;
  *head=node;
}

void insert_after_node(Node *node_to_insert_after,Node *new_node){
  new_node->next=node_to_insert_after->next;
  node_to_insert_after->next=new_node;
}

void printlist(Node *head){
  Node *tmp=head;
  while(tmp!=NULL){
    printf(" %d",tmp->value);
    tmp=tmp->next;
  }
}

Node *find_node(Node *head,int value){
  Node *tmp=head;
  while(tmp!=NULL){
    if(tmp->value==value) return tmp;
    tmp=tmp->next;
  }
  return NULL;
}

int main(){
  Node *head;
  Node *tmp;

  for(int i=0;i<25;i++){
    tmp=create_node(i);
    insert_at_head(&head,tmp);   
  }
  
  tmp=find_node(head,24);  
  insert_after_node(tmp,create_node(75));  
  printlist(head);
  
  return 0;
}

字符串
当我运行代码时,它给我24 75 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0,但当我用insert_after_node(head,create(75));替换insert_after_node(tmp,create_node(75));时,它给我24 75 23为什么?

pbgvytdp

pbgvytdp1#

如果你初始化head指针,这两种方法都能很好地工作:

Node *head = NULL;

字符串
局部变量在C中不是默认初始化的。

相关问题