撒旦 发表于 2007-12-26 22:28

我做的实验 关于双向循环链表的操作

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
        int data;
        struct node *prior,*next;
}Node;
Node* createnode(Node *head)
{
        head=(Node *)malloc(sizeof(Node));
        head->prior=head->next=NULL;
        return head;
}
Node* Findnode(Node *head,int i)
{
        Node *p;
        int j=1;
        p=head;       
        if(p->next==head)
                return NULL;
    while(j<i)
        {
           p=p->next;
           j++;
        }
        return p;
}
int insert(Node *head,int i,int value)
{
   
        Node *p,*q,*r;
        p=(Node *)malloc(sizeof(Node));
        p=head;
        if(p->next==NULL)
        {
                q=(Node *)malloc(sizeof(Node));
        q->data=value;
        p->next=q;
                q->next=p;
                p->prior=q;
                q->prior=p;
                return 0;
        }
        else
        {   
                q=(Node *)malloc(sizeof(Node));
            q=Findnode(head,i);
            r=(Node *)malloc(sizeof(Node));
            r->data=value;
            r->prior=q;
            r->next=q->next;
            q->next->prior=r;
            q->next=r;
                return 0;
        }
}
void Deletenode(Node *head,int i)
{
        Node *q;
        q=Findnode(head,i);
        q->prior->next=q->next;
        q->next->prior=q->prior;
        free(q);
}
void Displist(Node *head)
{
        Node *p=head->next;
        while(p!=head)
        {
                printf("%3d",p->data);
                p=p->next;
        }
        printf("\n");
}
void main()
{
        int m,n,k,i,j=11;
        Node *head=NULL;
        head=createnode(head);
        printf("初始化链表\n");
        for(i=1;i<13;i++)
        {
      insert(head,i,j);
          j++;
        }
        printf("show the list\n");
        Displist(head);
    printf("Input you want to insert to:(结点号和元素值) ");
        scanf("%d,%d",&m,&n);
        insert(head,m,n);
        Displist(head);
        printf("Input you want to delete to:(结点号) ");
        scanf("%d",&k);
        Deletenode(head,k);
        Displist(head);
}


页: [1]

编程论坛