天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

双向链表结构

Posted on 2012-02-28 00:34 hoshelly 阅读(153) 评论(0)  编辑 收藏 引用 所属分类: DS && Algorithm
#include<stdio.h>
#include<stdlib.h>
//双向链表结构
struct dlist
{
    int data;
struct dlist *front;//指向下一结点的指针
struct dlist *back;//指向前一结点的指针
};
typedef struct dlist dnode;
typedef dnode *dlink;
dlink createdlist(int *array,int len)
{
   dlink head;
   dlink before;
   dlink new_node;
   int i;
   //创建第一个结点,分配指针内存
   head=(dlink)malloc(sizeof(dnode));
   if(!head)
   return NULL;
   head->data=array[0];
   head->front=NULL;
   head->back=NULL;
   before=head;//指向第一个结点
   
   for(i=1;i<len;i++)//用循环创建其他结点
   {
      new_node=(dlink)malloc(sizeof(dnode));
  if(!new_node)
  return NULL;
  new_node->data=array[i];
  new_node->front=NULL;
  new_node->back=before;//将新结点指向前结点
  before->front=new_node;//将前结点指向新结点,构成循环链表
  before=new_node;//新结点成为前结点
}
return head;
}
//双向链表的输出
void printdlist(dlink head,dlink now)
{
   while(head!=NULL) //链表循环遍历
   {
      if(head == now)
  printf("#%d#",head->data);
  else
     printf("[%d]",head->data);
  head=head->front;
}
printf("\n");
}
void main()
{
   dlink head;
   dlink now=NULL;
   int list[6]={1,2,3,4,5,6};
   int select;
   
   head=createdlist(list,6);
   if(head==NULL)
   {
      printf("内存分配失败!\n");
  exit(1);
    }
now=head;
while(1)
{
   printf("链表内容是:");
   printdlist(head,now);
   printf("[1]往下移动 [2]往回移动 [3]离开 ==> ");
   scanf("%d",&select);
   switch(select)
   {
      case 1: if(now->front!=NULL)
           now=now->front;
   break;
  case 2: if(now->back!=NULL)
           now=now->back;
   break;
  case 3:  exit(1);
    }
}
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理