双链表

#include<stdio.h> 
#include<stdlib.h>
typedef struct NODE
{
 struct NODE *prior;
 struct NODE *next;
 int date;
}node;
typedef struct LIST
{
 node *head;
 node *last;
 int length;
}list;
int initlist(list *&h)
{
 
 h=(list *)malloc(sizeof(list));
 h->head=h->last=(node *)malloc(sizeof(node));
 if(NULL==h) return 0;
 
 h->head->next=h->last;
 h->last->prior=h->head;
 h->head->prior=h->last;
 h->last->next=h->head;
 
 h->length=0;
 return 1;
}
int crelist(list *&h,int data)
{
 node *p;
 p=(node *)malloc(sizeof(node));
 p->date=data;
 
 p->next=h->head->next;
 h->head->next->prior=p;
 p->prior=h->head;
 h->head->next=p;
 
 h->length++;
 return 1;
}
void show(list *r)
{
 printf("结果:\n");
 printf("length=%d\n",r->length);
 node *p;
 p=(node *)malloc(sizeof(node));
 p=r->last->prior;
 while(p!=r->last)
 {
  printf("%d ",p->date);
  p=p->prior;
 }
 printf("\n");
}
node *found(list *h,int n)
{
 node *p;
 p=h->last;
 int j=0;
 while(NULL!=p&&j<n)
 {
  p=p->prior;j++;
 }
 return p;
}
int insertlist(list *&h,int w,int s)
{
 if(w<1||w>h->length+1) return 0;
 node *p,*q;
 p=(node *)malloc(sizeof(node));
 q=(node *)malloc(sizeof(node));
 q=found(h,w);
 p->date=s;
 
 p->next=q->next;
 q->next->prior=p;
 p->prior=q;
 q->next=p;
 
 h->length++;
}
int del(list *&h,int n)
{
 if(n<1||n>h->length) return 0;
 node *q;
 q=(node *)malloc(sizeof(node));
 q=found(h,n);
 
 q->next->prior=q->prior;
 q->prior->next=q->next;
 
 h->length--;
 return 1;
}
int main()
{
 list *h;
 initlist(h);
 printf("输入数据个数:");
 int n,m;
 scanf("%d",&n);
 printf("输入数据:");
 while(n--)
 {
   scanf("%d",&m);
   crelist(h,m);
 }
 show(h);
 int a,b;
 printf("输入插入位置和数据:");
 scanf("%d%d",&a,&b);
 insertlist(h,a,b);
 show(h);
 printf("输入删除数据位置:");
 int c;
 scanf("%d",&c) ;
 del(h,c);
 show(h);
}
 
posted @ 2015-10-18 09:18  jarrem  阅读(72)  评论(0)    收藏  举报