单链表&双链表的头插入&尾插入

#include<stdio.h>
#include"stdlib.h" 

struct student 
{
int data;
struct student *pnext;
};
struct students
{
struct students *prev;
int data;
struct students *pnext;
};
struct student *create(int dat); //单链表创造一个节点。
struct students *shuangcreate(int dat); //双链表创造一个节点。

void insert_head(struct student* pH,struct student* news);//单链表头插入
void insert_head_shuang(struct students* pH,struct students* news);//双链表头插入
void insert_tail_shuang(struct students* pH,struct students* news);//尾插入
int main()
{
struct student *ph=create(0);
struct students *phs=shuangcreate(0);

insert_head(ph,create(1));
insert_head(ph,create(2));

insert_head_shuang(phs,shuangcreate(1));
insert_head_shuang(phs,shuangcreate(2));
insert_head_shuang(phs,shuangcreate(3));

/*
insert_tail_shuang(phs,shuangcreate(1));  //尾插入
insert_tail_shuang(phs,shuangcreate(2));

printf("%d.\n",ph->data);
printf("%d.\n",ph->pnext->data);
printf("%d.\n",ph->pnext->pnext->data);
*/
printf("%d.\n",phs->data);
printf("%d.\n",phs->pnext->data);
printf("%d.\n",phs->pnext->pnext->data);
printf("%d.\n",phs->pnext->pnext->pnext->data);

return 0;
}

struct student *create(int dat) //单链表创造一个节点。
{
struct student *p=(struct student*)malloc(sizeof(struct student));
if(NULL==p)
{
return NULL;
printf("节点分配失败");
}
p->data=dat;
p->pnext=NULL;
return p;
}

struct students *shuangcreate(int dat) //双链表创造一个节点。
{
struct students *p=(struct students*)malloc(sizeof(struct students));
if(NULL==p)
{
return NULL;
printf("双链表节点分配失败");
}
p->data=dat;
p->pnext=NULL;
p->prev=NULL;
return p;
}
void insert_head(struct student* pH,struct student* news)
{
news->pnext=pH->pnext;
pH->pnext=news;
}
void insert_tail_shuang(struct students* pH,struct students* news)   //双链表的尾插入
{
struct students* ph=pH;
while(NULL!=ph->pnext)
{
ph=ph->pnext;
printf("a\n");
}
ph->pnext=news;
news->prev=ph;
}
//画出双链表的节点链接情况
void insert_head_shuang(struct students* pH,struct students* news)  //双链表的头插入
{
struct students* p=pH;
news->pnext=p->pnext;
if(p->pnext!=NULL)           //考虑到只有一个头结点的情况。这里很重要 当第一次的时候p->pnext=NULL;
p->pnext->prev=news;
p->pnext=news;
news->prev=p;
}

接下来将会补齐单链表和双链表节点的 遍历 、逆序、和 删除 ;暂且放到这里,

猜你喜欢

转载自www.cnblogs.com/947033916-fwh/p/9862793.html
今日推荐