双链表的算法之删除节点
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* pPrev;
struct node* pNext;
};
struct node* create_node(int data)
{
struct node* p = (struct node*)malloc(sizeof(struct node));
if(NULL == p)
{
printf("create_node malloc failed\n");
return NULL;
}
p->data = data;
p->pPrev = NULL;
p->pNext = NULL;
return p;
}
void insert_tail(struct node* pH, struct node* new)
{
struct node* p = pH;
while(NULL != p->pNext)
{
p = p->pNext;
}
p->pNext = new;
new->pPrev = p;
}
void insert_head(struct node* pH, struct node* new)
{
new->pNext = pH->pNext;
if(NULL != pH->pNext)
pH->pNext->pPrev = new;
pH->pNext = new;
new->pPrev = pH;
}
void ergodic(struct node *pH)
{
struct node* p = pH;
while(NULL != p->pNext)
{
p = p->pNext;
printf("data = %d\n",p->data);
}
}
void forward(struct node *pTail)
{
struct node* p = pTail;
while(NULL != p->pPrev)
{
printf("data = %d\n",p->data);
p = p->pPrev;
}
}
int delete_node(struct node* pH, int data)
{
struct node* p = pH;
while(NULL != p->pNext)
{
p = p->pNext;
if(p->data == data)
{
if(NULL == p->pNext)
{
p->pPrev->pNext = NULL;
p->pNext = NULL;
free(p);
}
else
{
p->pPrev->pNext = p->pNext;
p->pNext->pPrev = p->pPrev;
free(p);
}
return 0;
}
}
printf("node find failed\n");
return -1;
}
int main()
{
struct node* pHeader = create_node(0);
insert_head(pHeader, create_node(1));
insert_head(pHeader, create_node(2));
insert_head(pHeader, create_node(3));
ergodic(pHeader);
delete_node(pHeader,1);
printf("after delete node\n");
ergodic(pHeader);
return 0;
}
|