现在的位置: 首页 > 综合 > 正文

C语言实现双向链表插入,删除

2013年10月19日 ⁄ 综合 ⁄ 共 1234字 ⁄ 字号 评论关闭

  要求:(1)演示程序以用户和计算机的对话方式执行。即在计算机终端上显示“提示信息”之后,
由用户在键盘上输入演示程序中规定的运算命令;相应的输入数据和运算结果显示在其后。
(2)程序执行的命令包括:建立双向链表;在指定的位置上插入一个元素;删除指定的元素
;输出结果;结束。
【测试数据】:
第一组:
输入1,3,5,7,9,11,13,15,建立双向链表。
在第5个元素前插入元素20;
删除元素11,19。
第二组:
输入2,4,6,8,10,12,14,20建立双向链表。
在第10个元素前插入元素25;
删除元素10,19。

编程:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct list{
int data;
struct list *next;
struct list *pre;
};
typedef struct list node;
typedef node *link;
link front=NULL,rear,ptr,head=NULL;

link push(int item){
link newnode=(link)malloc(sizeof(node));
newnode->data=item;
if(head==NULL)
{
  head=newnode;
  head->next=NULL;
  head->pre=NULL;
  rear=head;
}
else
{
  rear->next=newnode;
  newnode->pre=rear;
  newnode->next=NULL;
  rear=newnode;
}
return head;
}

void makenull(){          
front=NULL;
rear=NULL;
}

empty(){
if(front==NULL)
  return 1;
else
  return 0;
}

int tops(){
if(empty())
  return NULL;
else
  return rear->data;
}

void pop(){
if(empty())
  printf("stack is empty!\n");
else
  rear=rear->pre;
}

void display(link l){
    link p;
    p=l;
    while(p!=NULL){
  printf("%d->",p->data);
  p=p->next;
    }
}

void main(){
int n,i;
printf("input your first data!\n");
scanf("%d",&n);
front=push(n);
/*another data*/
for(i=0;i<3;i++)
{
  printf("input:\n");
  scanf("%d",&n);
  push(n);
}
ptr=front;
display(ptr);
printf("\n Please enter any key to pop");
pop();
ptr=front;
display(ptr);

}

抱歉!评论已关闭.