前几篇有了单链表的各种操作,双链表的操作与单链表类此,只是增加了一个前置指针而已,双链表的各种操作形同单链表,此处只给出双链表的创建,插入和删除操作:
代码已经过编译运行,确认无误(编译环境:codeblocks下的GNU GCC Compile)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define NUM 3
//对于双链表,注意,除最后一个节点的next指针指向NULL外,第一个节点的pre指针亦指向NULL
typedef struct NODE
{
int data;
struct NODE *next;
struct NODE *pre;
}dnode;
dnode* dcreat()
{
dnode *head,*p,*s;
int x,cycle = 1;
head = (dnode*)malloc(sizeof(dnode));
p = head;
while(cycle)
{
printf("\nPlease input the data:");
scanf("%d",&x);
if(0 != x)
{
s = (dnode*)malloc(sizeof(dnode));
s->data = x;
printf("%d",s->data);
p->next = s;
s->pre = p;
p = s;
}
else
cycle = 0;
}
head = head->next;
head->pre = NULL;
p->next = NULL;
// printf(" %d",head->data);
return head;
}
int length(dnode* head)
{
int n= 0;
dnode *p;
p = head;
while(p!=NULL)
{
p = p->next;
n++;
}
return n;
}
//打印双链表:
void dprint(dnode* head)
{
dnode* p;int n;
n = length(head);
p = head;
if(head!= NULL)
while(p!=NULL)
{
printf("%d\n",p->data);
p = p->next;
}
}
//双链表删除节点:
dnode* ddel_node(dnode* head,int num)
{
dnode* p1;
p1 = head;
while(num != p1->data && NULL != p1->next)
{
p1 = p1->next;
}
if(num == p1->data)
{
if(p1 == head)
{
head = head->next;
head->pre = NULL;
free(p1);
}
else if(NULL == p1->next)
{
p1->pre->next = NULL;
free(p1);
}
else
{
p1->pre->next = p1->next;
p1->next->pre = p1->pre;
free(p1);
}
}
else
{
printf("\nCould not find the num %d",num);
}
return head;
}
//双链表插入节点
dnode* dinsert(dnode* head,int num)
{
dnode* p0,*p1;
p1 = head;
p0 = (dnode*)malloc(sizeof(dnode));
p0->data = num;
while(p0->data > p1->data && p1->next != NULL)
{
p1 = p1->next;
}
if(p0->data <= p1->data)
{
if(head == p1)
{
p0->next = p1;
p0->pre = NULL;
p1->pre = p0;
}
else
{
p1->pre->next = p0;
p0->next = p1;
p0->pre = p1->pre;
p1->pre = p0;
}
}
else
{
p1->next = p0;
p0->pre = p1;
p0->next =NULL;
}
return head;
}
int main()
{
dnode* new_head = dcreat();
dprint(new_head);
dnode* head = ddel_node(new_head,NUM);
dprint(head);
head = dinsert(head,4);
dprint(head);
return 0;
}