線形表のシングルチェーンのヘッド挿入法、テール挿入法(C言語)

12072 ワード

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

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int ElemType;
typedef int Status;

/*    */
typedef struct LNode 
{
	ElemType data;
	struct LNode *next;
}LNode,*LinkList;

/*     */
void CreateListF(LinkList *L,ElemType a[],int n) 
{
	LinkList s;
	int i;
	*L = (LinkList)malloc(sizeof(LNode));
	(*L)->next = NULL;
	for (int i = 0; i < n;i++) {
		s = (LinkList)malloc(sizeof(LNode));
		s->data = a[i];
		s->next = (*L)->next;         // s        ,     
		(*L)->next = s;
	}
}

/*     */
void CreateListR(LinkList *L,ElemType a[],int n) 
{
	LinkList s, r;
	int i;
	(*L) = (LinkList)malloc(sizeof(LNode));//     
	r = (*L);                             //r        
	for (i = 0; i < n;i++) {             //        
		s = (LinkList)malloc(sizeof(LNode));  //      s
		s->data = a[i];                   // s  r  
		r->next = s;
		r = s;
	}
	r->next = NULL;                      //   next   NULL
}

void visit(ElemType e) 
{
	printf("%d",e);
}

void TraverseList(LinkList L,void (*visit)(ElemType)) 
{
	LinkList p = L->next;
	while (p) {
		visit(p->data);
		p = p->next;
	}
}

int main() 
{
	LinkList L,R;
	ElemType a[] = {1,2,3,4,5};
	CreateListF(&L,a,5);
	CreateListR(&R,a,5);
	TraverseList(L, visit);
	printf("
"
); TraverseList(R,visit); }