链表-在c开头插入

问题描述

我正在尝试在链表中插入 n 个字符。

#include <stdio.h>
#include <stdlib.h>
//Declare our linked list:
struct node{
  char ch;
  struct node* link;
};
//we Now intiate our head node the node which will identify our likedlist
struct node* head;
//prototype the insert function
void insert(char a);
//prototype the print function
void print();
int main() {
     //set the head to NULL
    head =NULL;
    char x;
    int i,n;
    printf("Enter how many Letter you wish for:\n");
    scanf("%d",&n);
    for(i=0;i<n;i++){
        printf("Enter the letter:\n");
        scanf("%c",&x);
        insert(x);
        print();
    }
    return 0;
}
//construct out insert function
void insert(char a){
    //we create a new block of memory in the heap here 
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    //store the passed arrgument  in ch 
    temp->ch=a;
    //fill the other room of the created block with the location/link
    //the prevIoUs node/block
    temp->link=head;
    //change the head to point to our newly created block
    head=temp;
}
void print(){
     //store the value of the head so we don't lose the head
      struct node* temp1=head; 
      //iterate through the nodes ant print the data in it until we hit the NULL value 
      printf("[");
      while(temp1->link != NULL){
          printf("%c",temp1->ch);
          //will go to the next node 
          temp1=temp1->link;
    }
     printf("]\n");
}

输出只是一团糟,我做错了什么? 输出示例: 输入您想要的字母数量: 3 输入字母: [] 输入字母: F [F] 输入字母: [ F]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)