Day4
思维导图
双向循环链表操作实现(多文件编译)
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
int n;
datatype element;
Doublelink head=NULL;
printf("please enter n:");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
printf("please enter %d element:",i+1);
scanf(" %c",&element);
// head=head_insert(head,element);
head=tail_insert(head,element);
}
output(head);
// head=head_delete(head);
// output(head);
head=tail_delete(head);
output(head);
return 0;
}
test.c
#include "head.h"
Doublelink create_node()
{
Doublelink p=(Doublelink)malloc(sizeof(struct Node));
if(NULL==p)
return NULL;
p->data='\0';
p->next=p;
p->priv=p;
return p;
}
Doublelink head_insert(Doublelink head,datatype element)
{
Doublelink s=create_node();
if(NULL==s)
return head;
s->data=element;
if(NULL==head)
{
head=s;
return head;
}
Doublelink p=head->priv;
s->next=head;
head->priv=s;
head=s;
head->priv=p;
p->next=head;
return head;
}
void output(Doublelink head)
{
if(NULL==head)
return;
Doublelink p=head;
puts("===正向===");
while(p->next!=head)
{
printf("%c\t",p->data);
p=p->next;
}
printf("%c\t",p->data);
puts("");
puts("===反向===");
do
{
printf("%c\t",p->data);
p=p->priv;
}while(p!=head->priv);
puts("");
}
Doublelink tail_insert(Doublelink head,datatype element)
{
Doublelink s=create_node();
if(NULL==s)
return head;
s->data=element;
if(NULL==head)
{
head=s;
return head;
}
Doublelink p=head->priv;
p->next=s;
s->priv=p;
s->next=head;
head->priv=s;
return head;
}
Doublelink head_delete(Doublelink head)
{
if(NULL==head)
return head;
if(NULL==head->next)
return NULL;
Doublelink p=head;
Doublelink q=head->priv;
head=head->next;
head->priv=q;
q->next=head;
free(p);
p=NULL;
return head;
}
Doublelink tail_delete(Doublelink head)
{
if(NULL==head)
return head;
if(NULL==head->next)
return NULL;
Doublelink p=head->priv;
Doublelink q=p->priv;
q->next=head;
head->priv=q;
free(p);
p=NULL;
return head;
}
head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef char datatype;
typedef struct Node
{
datatype data;
struct Node *priv;
struct Node *next;
}*Doublelink;
Doublelink create_node();
Doublelink head_insert(Doublelink head,datatype element);
void output(Doublelink head);
Doublelink tail_insert(Doublelink head,datatype element);
Doublelink head_delete(Doublelink head);
Doublelink tail_delete(Doublelink head);
#endif