单链表
#include <head.h>
typedef struct List{
int value;
struct List *pointe;
}*list;
list create_space()
{
list s=(struct List *)malloc(sizeof(struct List)); //向堆区申请空间
s->pointe = NULL;//初始化
s->value = 0;
return s;
}
list inserhead_list(list head,int value)
{
list s = create_space();
if(s == NULL)
{
return head;
}
s->value = value;
if(head == NULL)
{
head = s;
return head;
}else{
s->pointe = head;
head = s;
}
return head;
}
//头删
list delete_list(list head)
{
list p = head;
if(head == NULL)
{
free(head);
return head;
}
head = p->pointe;
free(p);
return head;
}
void output(list head)
{
if(head == NULL)
{
return;
}
while(head)
{
printf("%d ",head->value);
head = head->pointe;
}
}
int main(int argc,const char *argv[])
{
list head = NULL;
int value;
for (int i = 0; i < 5; i++)
{
printf("请输入插入的值:");
scanf("%d",&value);
head = inserhead_list(head,value);
}
output(head);
head=delete_list(head);
puts("");
output(head);
return 0;
}
双链表
#include <head.h>
typedef struct List{
int value;
struct List *next;
struct List *priv;
}*list;
list create_space()
{
list s=(struct List *)malloc(sizeof(struct List)); //向堆区申请空间
s->next = NULL;//初始化
s->priv = NULL;
s->value = 0;
return s;
}
头插
list inserhead_list(list head,int value)
{
list s = create_space();
if(s == NULL)
{
return head;
}
s->value = value;
if(head == NULL)
{
head = s;
return head;
}else{
s->next = head;
head->priv = s;
head = s;
}
return head;
}
//头删
list delete_list(list head)
{
list p = head;
if(head == NULL)
{
free(head);
return head;
}
head = p->next;
head->priv = NULL;
free(p);
return head;
}
int output(list head)
{
//1,判断链表为空
if(NULL ==head)
return -1;
//2.正向遍历
puts("正向遍历");
list p=head;
while(p->next!=NULL)
{
printf("%d\t",p->value);
p=p->next;
}
printf("%d\t",p->value);
puts("\n逆向遍历");
while(p!=NULL)
{
printf("%d\t",p->value);
p=p->priv;
}
puts("");
return 0;
}
int main(int argc,const char *argv[])
{
list head = NULL;
int value;
for (int i = 0; i < 5; i++)
{
printf("请输入插入的值:");
scanf("%d",&value);
head = inserhead_list(head,value);
}
output(head);
head=delete_list(head);
puts("------------");
output(head);
return 0;
}