如何解决链表-在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 举报,一经查实,本站将立刻删除。