数据结构之双向链表的插入

#include<iostream>
#include<malloc.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
typedef struct node
{
char data;
struct node *prior;
struct node *next;
} lnode,*linklist;

int init(linklist *head)
{
(*head)=(linklist)malloc(sizeof(lnode));
if(!head)//头结点为空的时候执行if语句的内容
return -1;
(*head)->next=*head;
(*head)->prior=*head;
return 1;
}
int creat(linklist head,int n)
{
lnode *s,*q;
int i;
char e;
q=head;
for(i=1;i<=n;i++)
{
cout<<"输入第"<<i<<"个元素" ;
cin>>e;
s=(linklist)malloc(sizeof(lnode));
s->data=e;//注意双链表的结构
s->next=q->next;
q->next=s;
s->prior=q;
head->prior=s;
q=s;
}

return 1;
}
linklist get(linklist head,int i)
{
lnode *p;
int j;
p=head->next;
j=1;
while(p!=head&&j<i)
{
p=p->next;
j++;
}
if(p==head||j>i)
{
return NULL;
}
return p;
}

int insert(linklist h,int i,char e)//注意e是什么数 是int还是char
{
lnode *p,*s;
int j=0;
p=get(h,i);
if(!p)
return 0;
s=(linklist)malloc(sizeof(lnode));
if(!s)
return -1;
s->data=e;
s->prior=p->prior;
p->prior->next=s;
s->next=p;
p->prior=s;
return 1;
}

void dis(linklist head)
{
lnode *p;
p=head->next;
while(p!=head)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
linklist h;
int n;
int pos;
char e;
init(&h);
cout<<"输入元素个数:"<<endl;
cin>>n;
creat(h,n);
cout<<"链表中元素:"<<" ";
dis(h);
cout<<"输入插入元素及位置:";
cin>>e;
cin>>pos;//尴尬 cout和cin弄反了

insert(h,pos,e);
printf("插入元素后的链表");
dis(h);
}

原文地址:https://www.cnblogs.com/mykonons/p/6595174.html