双向链表的建立插入与删除
/*注意因为建表时用了字符型数据所以输入数字时只能输0~9*/
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node *pre;
struct node *next;
}node, *list;
list TailCreat(); //尾插法创建链表
void Insert(list head, int x, char value, int length);//向链表特定位置插入一个元素
void Delete(list head, int x, int length); //删除特定位置的元素
int Length(list head); //链表的长度
void print(list head); //输出链表
int main(void)
{
list head;
int length, x;
char value;
head = TailCreat();
length = Length(head);
print(head);
printf("\n");
printf("请输入要插入的数:");
scanf("%c",&value);
printf("%c\n",value);
printf("请输入要插入的位置:");
scanf("%d",&x);
printf("%d\n",x);
Insert(head, x, value, length); //向链表特定位置插入一个元素
print(head);
printf("请输入要删除元素的位置");
scanf("%d",&x);
Delete(head, x, length); //删除特定位置的元素
print(head);
return 0;
}
list TailCreat() //尾插法创建链表
{
list head;
node *p;
char c;
int flag = 1;
head = (node *)malloc(sizeof(node));
if(!head)
printf("创建错误!");
p = head;
p->next = NULL;
while(flag == 1)
{
node *w;
w = (node *)malloc(sizeof(node));
printf("请输入数据:");
c = getchar();
flushall();
if(c != '$')
{
w->data = c;
p->next = w;
w->pre = p;
p = w;
}
else
{
flag = 0;
p->next = NULL;
}
}
return head;
}
int Length(list head) //链表的长度
{
node *p;
int i = 0;
for(p = head->next; p != NULL; p = p->next)
i++;
return i;
}
void Insert(list head, int x, char value, int length)//向链表特定位置插入一个元素
{
node *p, *w;
int i = 1;
p = head->next;
if(x > length)
{
printf("插入错误!\n");
}
else
{
w = (node *)malloc(sizeof(node));
w->data = value;
while(i < x)
{
p = p->next;
i++;
}
w->pre = p->pre;
p->pre->next = w;
p->pre = w;
w->next = p;
}
}
void Delete(list head, int x, int length) //删除特定位置的元素
{
int i = 1;
node *p;
p = head->next;
if(x > length)
{
printf("删除错误!\n");
}
else
{
for(i = 1; i <x; i++)
{
p = p->next;
}
p->pre->next = p->next;
p->next->pre = p->pre;
free(p);
}
}
void print(list head) //输出链表
{
node *p;
for(p = head->next; p != NULL; p = p->next)
printf("%c ",p->data);
printf("\n");
}