编辑代码

#include <stdio.h>
#include <stdlib.h>

typedef struct CLNode{
	int data;
	struct CLNode *next;
}CLNode,*LinkList;

void init(LinkList &L)
{
	L = (CLNode *)malloc(sizeof(CLNode));
	L->next = L;//初始化让头结点指向自己 
}

//后插结点 
void InsertNextNode(LinkList &L,int e)
{
	CLNode *s = (CLNode *)malloc(sizeof(CLNode));
	s->data = e; 
	s->next = L->next; 
	L->next = s;
}
//尾插法 
void TailInsert(LinkList &L)
{
	int e,n;
	printf("输入要输入元素的个数:\n");
	scanf("%d",&n);
	printf("输入元素的值:\n");
	for(int i=0;i<n;i++)
    {
		scanf("%d",&e);
		CLNode *p = (CLNode *)malloc(sizeof(CLNode));
		p = L;
		while(p->next != L)
        {//第一个节点进行特殊处理 
			if(L->next == L)
            {//头结点为空,则创建一个新结点 
				CLNode *p = (CLNode *)malloc(sizeof(CLNode));
				L->next = p;
				p->next = L;
				p->data = e;
			}
			p = p->next;
		}
		InsertNextNode(p,e);
	}
}

//前插结点 
void InsertPriorNode(LinkList &L,int e)
{
	CLNode *s = (CLNode *)malloc(sizeof(CLNode));
	//把L存入s,再令L存入新数据 
	s->data = L->data;
	s->next = L->next;
	L->next = s;
	L->data = e;
}

//头插法 
void HeadInsert(LinkList &L)
{
	int n,e;
	printf("输入要输入元素的个数:\n");
	scanf("%d",&n);
	printf("输入元素的值:\n");
	for(int i=0;i<n;i++)
    {
		scanf("%d",&e);
		if(L->next == L)
        {
			CLNode *p = (CLNode *)malloc(sizeof(CLNode));
			L->next = p;
			p->next = L;
			p->data = e;
		}
		else
        {
			InsertPriorNode(L->next,e);
		}
	}
}

void show(LinkList &L)
{
	CLNode *p = L;
	while(p->next != L)
    {
		p = p->next;
		printf("%d ",p->data);
	}
	printf("\n");
}

int main(){
	CLNode *L,*K;
	init(L);
	printf("采用尾插法:\n");
	TailInsert(L);
	show(L);
	
	init(K);
	printf("采用头插法:\n");
	HeadInsert(K);
	show(K);  
	return 0;
}