普通单链表的创建与遍历

 前插法与后插法建立单链表

#include 
#include 

typedef int Datatype;
typedef struct Node{
	Datatype data;
	struct Node * next;
}Node, *LinkList;

LinkList  CreatList(void);
void Traverse(LinkList);

int main(void){
	LinkList L = NULL;
	L = CreatList();
	Traverse(L);
	
	
	return 0;
} 

LinkList CreatList(void){
	int len, i, val;
	Node * pHead = (Node *)malloc(sizeof(Node)); //创建头结点,分配内存 
	if(NULL == pHead){
		printf("分配失败\n");
		exit(-1);
	}
	//声明尾节点并初始化 
	Node * pTail = pHead;
	pTail->next = NULL;
	
	printf("请输入单链表长度\n");
	scanf("%d",&len);
	for(i = 1; i<= len; ++i){
		printf("请输入单链表第%d个元素值\n",i);
		scanf("%d",&val);
		Node * pNode = (Node*)malloc(sizeof(Node));
		if(NULL==pNode){
			printf("内存分配失败\n");
			exit(-1);
		}
		pNode->data = val;
//		//尾插法 
//		pTail->next = pNode;
//		pNode->next	= NULL;
//		pTail = pNode;
		//头插法 
		pNode->next	= pHead->next;
		pHead->next = pNode;
		
		
	} 
	
	return pHead;
}
void Traverse(LinkList 	L){
	Node *p =L->next;
	while(p){
		printf("%d ",p->data);
		p = p->next;
	}
	
}

 

你可能感兴趣的:(日常编程)