您的位置:首页 > 其它

双向链表建立、插入删除

2018-03-20 10:13 218 查看
#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
struct Node* pre;//指向上一个
int data;
struct Node *next;//指向下一个
}STU,*nodes;

nodes creatnew()//建立头结点
{
nodes head;
head=(nodes)malloc(sizeof(STU));
head->pre=NULL;
head->next=NULL;
return head;
}

nodes creat_list(nodes head)//创建链表
{
int i,n;
nodes p1,p2;
p2=head;
printf("请输入要创建的节点个数:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p1=(nodes)malloc(sizeof(STU));
scanf("%d",&p1->data);
p2->next=p1;
p1->pre=p2;
p2=p1;
}
p2->next=NULL;
return p2;
}

void put(nodes head)//输出
{
nodes p;
p=head;
while(p->pre!=NULL)
{

printf("%d\n",p->data);
p=p->pre;
}
}

nodes Delete(nodes head)//删除
{
int num;
nodes p1,p;
p1=p=head;
printf("请输入要删除的数据\n");
scanf("%d",&num);
p=p->pre;
do
{
if(p->data==num)
{
p1->pre=p->pre;
p1=p;
//free(p);
return head;
}
else
{
p1=p;
p=p->pre;
}
}while(p!=NULL);

}

nodes insert(nodes head)//插入
{
int num;
nodes p,p1,news;
p=p1=head;
printf("请输入要插入的数据:\n");
scanf("%d",&num);
while(p!=NULL)
{
p1=p;
p=p->next;
if(p->data>num)
{
news=(nodes)malloc(sizeof(STU));
news->data=num;
p1->next=news;
news->pre=p1;
news->next=p;
p->pre=news;
return head;
}

}

}

int main()
{
nodes head;
head=creatnew();
head=creat_list(head);
put(head);
Delete(head);
put(head);
//insert(head);
//put(head);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: