我老师要求用0来结束创建双向链表,可是我每次打0都死在那里。不知什么原因。望大家指教!
问题还不少啊;
对head没有赋值,根本成不了链表;对p最后一次申请的空间没有释放,造成内存泄漏;既然是双向链表没有对prec指针赋值,写法也不是很规范;
不好意思,可能有些严厉,但作为初学者,我觉得代码写的规范写比较好,易于别人理解;以下是我的链表,在VC和gcc下调试通过,你可以看一下,不当之处也请指正;
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
struct _list
{
int data;
struct _list *pre;
struct _list *next;
};
typedef struct _list node;
typedef node *link;
link create_list() //create the double list
{
link head, newnode, point;
int inputValue;
head = NULL;
printf("input nums,end with zeros!\n");
while(1)
{
scanf("%d",&inputValue);
if(!inputValue) //end with zero
break;
newnode = (link)malloc(sizeof(node)); //insert new node
assert(newnode);
newnode->data = inputValue;
newnode->pre = NULL;
newnode->next = NULL;
if(!head){ //empty list
head = newnode;
point = head;
}else{
newnode->pre = point;
point->next = newnode;
point = newnode;
}
}
return head;
}
void print_list(link head) //print list
{
while(head)
{
printf("%-5d",head->data);
head = head->next;
}
printf("\n");
return;
}
int main(void)
{
link head;
head = create_list();
print_list(head);
return -1;
}