|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我真的崩溃了,大佬们告诉我这个程序哪里出问题了,它没报错但在DEV C++上就是不能运行
- #include <stdio.h>
- #include <stdlib.h>
- struct Node {
- int num;
- struct Node *next;
- };
- //void touchafa(struct Node **head1, int input); 需要这一行吗?为什么?
- void touchafa(struct Node **head1, int input) {
- //struct Node *temp;
- //struct Node *p = (struct Node *)malloc(sizeof(struct Node));
- struct Node *p = malloc(sizeof(struct Node)); // 为什么要强制转换呢?少写几个字符不好吗?
- p->num = input;
- /*
- if(*head1 == NULL) {
- *head1 = p;
- p->next = NULL;
- } else {
- temp = *head1;
- *head1 = p;
- p->next = temp;
- }
- */
- p->next = *head1;
- *head1 = p;
- }
- //void weichafa(struct Node **head2, int input); // 你在做什么?
- void weichafa(struct Node **head2, int input) {
- //static struct Node *store; // 这么写,用的时候不方便
- static struct Node **store;
- //struct Node *p = (struct Node *)malloc(sizeof(struct Node));
- //struct Node *p = malloc(sizeof(struct Node)); // 少写上几个字符吧,写那么多干嘛?
- struct Node *p = malloc(sizeof(*p)); // 一个更好的写法
- // 这样写是为了在修改p的类型之后不需要修改sizeof里面的类型
- // 少改一个地方就少一个出错的可能
- p->num = input;
- p->next = NULL;
- /*
- if(*head2 == NULL) {
- *head2 = p;
- p->next = NULL;
- } else {
- store->next = p;
- p->next = NULL;
- }
- store = p;
- */
- if(!store) store = head2;
- *store = p;
- store = &p->next;
- }
- //void printnum(struct Node *head); // 同上
- void printnum(struct Node *head) {
- struct Node *p = head;
- while(p != NULL) {
- printf("%d ", p->num);
- p = p->next;
- }
- putchar('\n');
- }
- void free_list(struct Node *head) {
- if(!head) return;
- free_list(head->next);
- free(head);
- }
- int main() {
- int input;
- //struct Node *head1;
- //struct Node *head2;
- // 你不初始化吗?为什么?
- struct Node *head1 = NULL;
- struct Node *head2 = NULL;
- printf("下面开始录入链表,录入完毕后将检查这是否是回文链表(即顺着倒着读结果一样的链表):\n ");
- while(1) {
- printf("请输入一个整数(输入-1表示结束):\n");
- scanf("%d", &input);
- /*
- if(input == -1) {
- break;
- } else {
- touchafa(&head1, input);
- weichafa(&head2, input);
- }
- */
- // 等价修改
- // else 什么?
- // 都跳出去了还else ?
- if(input == -1) break;
- touchafa(&head1, input);
- weichafa(&head2, input);
- }
- printf("录入的链表是 ");
- printnum(head2);
- // 你这么写,你还释放内存不了?
- // 申请了内存不释放就和借了东西不还一样恶心
- // 都像你这么写程序,别说16GB,就是16EB的内存也不够你用呀
- // 你这一直借东西不还,之后人家就不借给你了
- // 系统哪有那么多内存给你这么整?
- // 一直申请内存不释放,系统也没内存了,还怎么分配给你?
- /*
- while(head1 != NULL) {
- if(head1->num == head2->num) {
- head1 = head1->next;
- head2 = head2->next;
- } else {
- break;
- }
- }
- if(head1 == NULL && head2 == NULL) {
- printf("经检查,该链表确实是回文链表!\n");
- } else {
- printf("一眼就看出,这不是回文链表!\n");
- }
- */
- struct Node *t1 = head1;
- struct Node *t2 = head2;
- while(t1 != NULL && t2 != NULL) {
- if(t1->num != t2->num) break;
- t1 = t1->next;
- t2 = t2->next;
- }
- if(t1 == NULL && t2 == NULL) {
- printf("经检查,该链表确实是回文链表!\n");
- } else {
- printf("一眼就看出,这不是回文链表!\n");
- }
- // 释放内存,不要借了不还,这样很不礼貌
- free_list(head2);
- free_list(head1);
- return 0;
- }
复制代码
|
|