双向链表

#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
 int data;
 struct list*left;
 struct list*right;
}List;
void insert_list_2nd(List*head,int data);
void insert_list_last(List*head,int data);
void insert_list_order(List*head,int data);
void print_list(List*head);
void delete_list(List*head,int value);

int main()
{ int i;
 List*head=(List*)malloc(sizeof(List)); 
 head->data=-1;
 head->left=head->right=NULL;
// for(i=0;i<10;i++)
  //insert_list_last(head,i);
//  insert_list_2nd(head,i);
 for(i=9;i>=0;i--)
  insert_list_order(head,i);
 print_list(head);
 for(i=0;i<10;i++)
  delete_list(head,i);
 print_list(head);
 
} 

void insert_list_2nd(List*head,int data)
{
 List*newnode=(List*)malloc(sizeof(List));
 newnode->data=data;
 newnode->right=head->right;
 head->right=newnode;
 newnode->left=head;
 if(newnode->right)
 {
  newnode->right->left=newnode;
 }   
}
void insert_list_last(List*head,int data)
{ List*newnode=(List*)malloc(sizeof(List));
 newnode->data=data; 
 while(head->right)
 {
  head=head->right;
 }
 head->right=newnode;
 newnode->left=head;
 newnode->right=NULL;
   
}
void insert_list_order(List*head,int data)
{ List*newnode=(List*)malloc(sizeof(List));
 newnode->data=data; 
 while(head->right && head->right->data<data)
 {
  head=head->right;
 }
 if(head->right==NULL)
 {
  head->right=newnode;
  newnode->left=head;
  newnode->right=NULL;  
 } 
 else
 {
  newnode->right=head->right;
  head->right=newnode;
  newnode->left=head;
  newnode->right->left=newnode; 
 }
}
void print_list(List*head)
{
 while(head)
 {
  printf("%d\n",head->data);
  head=head->right;
 } 
}
void delete_list(List*head,int value)
{
 List *temp;
 while(head->right && head->right->data!=value)
 {
  head=head->right;
 }
 if(head->right==NULL)
 {
  printf("don't have %d\n",value);
  return ;
 } 
 else
 {
  temp=head->right;
  head->right=temp->right;
  if(temp->right) 
  {
   temp->right->left=head;
  }
  free(temp);
 }
  
}

 

posted @ 2013-12-31 15:24  博园少主  阅读(139)  评论(0编辑  收藏  举报