带表头结点的创建

//先创建一个数据域值为空,指针域指向空的结点,作为头结点
//然后遍历数组读取数据建立结点,尾插或者头插结点,建链

#include<stdio.h>
#include<stdlib.h>
#define N 5 
typedef struct node{
	int data;
	struct node *next;
}ElemSN;
ElemSN *createlink(int a[])
{
	ElemSN *h,*tail;
	h=tail=(ElemSN *)malloc(sizeof(ElemSN));
	h->next=NULL;
	/*尾插 
	for(int i=0;i<N;i++){
		tail=tail->next=(ElemSN *)malloc(sizeof(ElemSN));
		tail->data=a[i];
		tail->next=NULL;
	}*/
	
	//头插 
	 for(int i=N-1;i>=0;i--){
		tail=(ElemSN *)malloc(sizeof(ElemSN));
		tail->data=a[i];
		tail->next=h->next;
		h->next=tail;
	}
	return h;
}
void prelink(ElemSN *h)
{
	ElemSN *p;
	for(p=h;p->next;p=p->next){
		printf("%6d",p->next->data);
	}
}
int main()
{
	int a[5]={3,2,5,8,4};
	ElemSN *head;
	//创建带表头的单向链表
	 head=createlink(a);
	 //输出链表
	 prelink(head);
	 return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_42727102/article/details/88858151