中间因为指针的运用错误 而导致一系列问题 指针还需要在实战中加强理解
# ifndef dList
# define dList
/************************************************************************/
/* 实现双向链表 用结构来实现
*/
# define ENDSYMBOL -1
//DListNode * head = NULL;
typedef struct _DListNode
{
struct _DListNode* pre;
struct _DListNode* next;
int data;
}DListNode;
int DListSize;
/*bool dList_malloc(int n)
{
return (malloc(sizeof(DListNode)*n)!=NULL);
}*/
void dlist_init(DListNode *& head)
{
//DListNode tail;//其他的没细看,你的DListNode tail;这里的tail是局部变量应该不行,函数返回后就成了野指针了。
DListNode *tail = (struct _DListNode*)malloc(sizeof(struct _DListNode));
//*head = (struct _DListNode*)malloc(sizeof(struct _DListNode));
(head)->next = tail;
(head)->pre = NULL;
tail->pre = head;
tail->next = NULL;
DListSize = 1;
}
void dList_insert(int a,DListNode *& head)
{
struct _DListNode* node;
node = (struct _DListNode*)malloc(sizeof(struct _DListNode));
node ->data = a;
node ->next = NULL;
node ->pre = NULL;
if(DListSize == 1)//if(*head == NULL)
{
//struct _DListNode* temp;
// temp = struct _DListNode*malloc(sizeof(struct _DListNode));
// *head = node;
// (*head) ->pre = NULL;
// (*head) ->next = NULL;
(head)->data = a;
DListSize ++;
}
else if(DListSize == 2)
{
(head)->next->data = a;
DListSize ++;
}
else
{
struct _DListNode* temp;
node = (struct _DListNode*)malloc(sizeof(struct _DListNode));
temp = head;
while(temp->data < a && temp->next!=NULL)
temp=temp->next;
/*node->next = temp->next;
temp->next->pre = node;
node->pre = temp;
temp->next = node;*/
node->next = temp->next;
if((temp)->next )
temp->next->pre = node;
node->pre = temp;
temp->next = node;
node->data = a;//之前没有加这个 代码运行结果有误 但是我之前已经赋值了
DListSize ++;
}
}
bool dList_delete(int index, DListNode *& head)
{
if(index <=0 || index > DListSize)
return false;
DListNode *temp;
int i ;
temp = head;
if(index == 1)
{
head->next->pre = NULL;
head = head->next;
free(temp);
temp = NULL;
}
else
{
for(i = 1; i < index ; i ++)
temp = temp->next;
temp->next->pre = temp->pre;
temp->pre->next = temp->next;
}
return true;
}
void dList_print(DListNode *& head)
{
DListNode * node = (head);
while(node!=NULL)
{
printf("%d\t",node->data);
node = node->next;
}
}
# endif
posted on 2010-08-03 23:30
付翔 阅读(218)
评论(0) 编辑 收藏 引用 所属分类:
linux 及 c相关