9.5 链表动态创建之头插法

头插法:新节点进来称为链表头,不断插入,头一直都是最新的节点。

#include 
#include 
struct Test
{
	int data;
	struct Test *next;
};

void printLink(struct Test *head)
{
	while(1){
		if(head != NULL){
		printf("%d ",head->data);
		head = head->next;
		}else{
			printf("\n");
			break; 
		}
	}
}




struct Test* creatFromHead(struct Test *head)
{
	struct Test *new;
	while(1){
			new = (struct Test *)malloc(sizeof(struct Test));
			printf("input your new node data:\n");
			scanf("%d",&(new->data));
			if(new->data == 0){
				printf("0 out\n");
				return head;
			}
			if(head = NULL){
				head = new;
			}else{
				new->next = head;
				head = new;
			}
	}	
	return head;
}

int main(){
	int i;
	struct Test *head = NULL;
	head = creatFromHead(head);
	printLink(head);
	
	
	
	
	return 0;
}

你可能感兴趣的:(链表,数据结构)