【发布时间】:2016-08-27 10:00:45
【问题描述】:
我是 c 新手。我有以下创建双链表的代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct Dnode
{
char c;
struct Dnode *left;
struct Dnode *right;
}Dnode;
void insert(Dnode *,char);
void unshift(Dnode *,char);
void travel(Dnode *);
int main(){
Dnode *cur = (Dnode *)malloc(sizeof(Dnode));
Dnode *head = NULL;
head = cur;
cur -> c = 'a';
printf("Cur -> c: %c\n",cur->c);
cur ->left = NULL;
cur -> right = (Dnode *)malloc(sizeof(Dnode));
cur->right->c = 'b';
cur->right->left = cur;
cur = cur->right;
travel(head);
system("pause");
return 0;
}
void reset(Dnode *h){
while(h->left)
h=h->left;
}
void travel(Dnode *head){
printf("Traversing all nodes of list:\n");
while(head->right){
printf("Received char from node %c\n",head->c);
head = head->right;
}
//reset(head);
}
void insert(Dnode * d,char c){
Dnode *t = d;
while(t ->right)
t=t->right;
t->right = (Dnode *)malloc(sizeof(Dnode));
if(t->right){
t->right->c = c;
t= t->right;
t->right = t->left = NULL;
}
}
void unshift(Dnode *d,char cc){
Dnode *t =(Dnode *)malloc(sizeof(Dnode));
t = d->right;
t->left =NULL;
d->left = t;
d = t;
}
问题是在调用 travel() 之后所有的节点都被打印出来了。 它打印“从节点 a 接收到的字符” 和“从节点 b 接收到的字符”
但是 Windows 给我一个错误,说程序已经崩溃。有什么想法吗?我想要一个详细的答案,以避免将来出现类似的问题。
【问题讨论】:
-
使用调试器单步调试程序,看看哪里出了问题。
-
你从未初始化过
cur->right->right。 -
这看起来不像是一个“简单”的程序。 :-P
-
@kiner_sah 哈哈是真的。
标签: c doubly-linked-list