链表函数 (接口实现)范例

头文件(函数接口,链表类型定义)

typedef struct node* link;
struct node 
{
	int item;
	link next;
};

typedef link Node;

void initNodes(int);
void freeNode(link);
link newNode(int);
void insertNext(link,link);
link deleteNext(link);
link Next(link);
int Item(link);

函数接口实现

#include<stdlib.h>
#include "list.h"

link freelist;

void initNodes(int N)
{
	freelist=malloc((N+1)*(sizeof *freelist));
	for(int i=0; i<N+1; i++)
		freelist[i].next=&freelist[i+1];
	freelist[N].next=NULL;
}
link newNode(int i)
{
	link x=deleteNext(freelist);
	x->item=i; x->next=x;
	return x;
}
void freeNode(link x)
{
	insertNext(freelist, x);
}
void insertNext(link x, link t)
{
	t->next=x->next;
	x->next=t;
}
link deleteNext(link x)
{
	link t=x->next;
	x->next=t->next;
	return t;
}
link Next(link x)
{
	return x->next;
}
int Item(link x)
{
	return x->item;
}

主程序

#include <stdio.h>
#include "list.h"

int main(void)
{
    int N=10,M=5;
    Node t, x;
    
    initNodes(N);
    x=newNode(1);
   // x->next=x;
    insertNext(x,x);
    for(int i=2; i<=N; i++)
	{
		t=newNode(i);
		insertNext(x,t); 
		x=t;
	}
	while(x!=Next(x))
	{
		for(int i=1; i<M; i++)
			x=Next(x);
		freeNode(deleteNext(x));
	}
	printf("%d",Item(x));
    
    return 0;
}

 

posted on 2018-02-28 13:26  MACHINE_001  阅读(98)  评论(0编辑  收藏  举报

导航