超详细---链表头插法

# include<stdio.h>
# include<stdlib.h>
using namespace std;

typedef struct node
{
	int data;
	node * next;
}Node;
#if 0
头插法: 
1.在主函数中创建一个头指针;			···Node * phead = creat_list();
2.在函数中首先创建一个空链表,再通过插入的节点       ···Node * head = (Node *)malloc(sizeof(Node));
  组成一个完整的链表;			   	   head->next = NULL;
3.让新来的节点有所指向(避免打乱原有的指向关系)	···cur->next = head->next;
4.让首节点指向新来的节点				···head->next = cur;
#endif 

Node * creat_list_first()
{
	Node * head = (Node *)malloc(sizeof(Node));
	head->next = NULL;
	Node * cur = NULL;
	int data;
	printf("请输入节点数据:\n");
	scanf("%d", &data);

	while (data)
	{
		cur = (Node*)malloc(sizeof(Node));
		cur->data = data;
		cur->next = head->next;
		head->next = cur;
		scanf("%d", &data);
	}
	return head;
}

void show_list(Node * head)
{
	head = head->next;
	while (head)
	{
		printf("%d\n",head->data);
		head = head->next;
	}
}

int main()
{
	Node * phead = creat_list_first();
	show_list(phead);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33661910/article/details/86627161