#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct DoubleLinkNode
{
int data;
struct DoubleLinkNode *prev;
struct DoubleLinkNode *next;
}Node;
/* 创建一个带头节点的双向链表 */
Node* Create_Double_link()
{
Node* phead;
Node* pnew;
Node* plast;
int i,n;
phead = (Node*)malloc(sizeof(Node));
assert(NULL != phead);
phead->prev = NULL;
phead->next = NULL;
printf("please input the length of the double linked list:");
scanf("%d",&n);
if(n!=0)
{
plast = phead;
for(i = 0 ; i < n;i++)
{
pnew=(Node*)malloc(sizeof(Node));
printf("向第%d个节点输入数据:",i+1);
scanf("%d",&pnew->data);
plast->next = pnew;
pnew->prev = plast;
plast = plast->next;
}
pnew->next=NULL;
}
return phead;
}
/* 输出每一个节点的数据 */
void print(Node* head)
{
Node* temp;
int j=0;
temp = head;
while(temp->next != NULL)
{
j++;
printf("输出第%d个节点的数据:%d\n",j,temp->next->data);
temp=temp->next;
}
}
/* 插入节点 */
int InsertNode(Node* head)
{
Node* new;
Node* p=head;
int i=0;
int n;
Node* pnext;
printf("please input the location which is inserted:");
scanf("%d",&n);
while((i<n-1) && (p!=NULL))
{
i++;
p = p->next;
}
if(p==NULL)
{
return 1;
}
else
{
new=(Node*)malloc(sizeof(Node));
printf("请在新插入的节点中输入数据:");
scanf("%d",&new->data);
/*
第一步:首先找到插入位置,节点 s 将插入到节点 p 之前
第二步:将节点 s 的前驱指向节点 p 的前驱,即 s->prior = p->prior;
第三步:将节点 p 的前驱的后继指向节点 s 即 p->prior->next = s;
第四步:将节点 s 的后继指向节点 p 即 s->next = p;
第五步:将节点 p 的前驱指向节点 s 即 p->prior = s;*/
if(p->next == NULL) //p是最后一个节点,新的节点在最后
{
p->next = new;
new->prev = p;
}
else
{
pnext = p->next; //p为前驱节点,新节点将插入在p和pnext之间
new->prev = pnext->prev;
pnext->prev->next = new;
new->next = pnext;
pnext->prev = new;
}
}
return 0;
}
/*删除节点 */
int DeleteNode(Node*head)
{
Node*p=head;
Node*ptr;
int n;
int i=0;
printf("please input the node that you will delete:");
scanf("%d",&n);
while((i<n-1) && (p!=NULL))
{
i++;
p=p->next;
}
if(p==NULL)
{
return 1;
}
if(p->next->next!=NULL) //删除的不是最后一个节点
{
ptr=p->next;
ptr->next->prev=p;
p->next = ptr->next;
free(ptr);
ptr = NULL;
}
else //删除的是最后一个节点
{
ptr=p->next;
p->next = ptr->next;
free(ptr);
ptr = NULL;
}
return 0;
}
/* 主函数 */
int main(int argc,char**argv)
{
Node* head;
head=Create_Double_link();
InsertNode(head);
DeleteNode(head);
print(head);
return 0;
}
![]()