Sneak () in idle stole [C language articles] - (9) list

Disclaimer: This article from the original articles of cold water, migrate to the personal blog site https://dp2px.com. https://blog.csdn.net/lxq_xsyu/article/details/23968353

At least we were able to store data in two structures

Array

1 needs a continuous block of storage space. Memory may not

2. Insert the elements, remove elements very low efficiency.

3. Finding data faster

List

1. Find a low efficiency

2. do not need a continuous memory space

3. Insert delete elements of high efficiency

Computer Terms

Head pointer: storing the address of the head node pointer variable

The first node:

The data types and the first node exactly the same

In front of the head node is the first node that node

The first node does not store valid data

Set the first node purpose is to facilitate the operation list

The first node: storing the first valid data node

Tail node:

A storage node last valid data

Tail node pointer field is empty (null)

Head pointer ----> ---- head node> ( head node -----> list ------> tail node )  () within the valid data is

Only need to know a list head pointer can be determined (tail node pointer field is null)

2012年2月6日7:30:48

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>

struct Node{
	int data;
	struct Node * pNext;
};

struct Node * create_list();
void traverseList(struct Node *);

int main(void){
	struct Node * pHead = NULL;  //定义头指针
	pHead = create_list();  //构造链表,返回头结点地址
	traverseList(pHead);  //输出链表

	return 0;
}

struct Node * create_list(void){
	int len;
	int i;
	int val;

	//创建一个头结点
	struct Node * pHead = (struct Node *)malloc(sizeof(struct Node)); 
	if(NULL == pHead){
		printf("分配失败,程序终止!\n");
		exit(-1);
	}
	struct Node * pTail = pHead;  //将头结点的地址给指针变量pTail使pTail指向头结点
	pTail->pNext = NULL;  //头结点的结构体元素(下一个节点地址)赋值
	printf("请输入你要创建链表的节点个数:len = ");
	scanf("%d", &len);

	for(i=0; i<len; i++){
		printf("请输入第%d个节点的值:", i+1);
		scanf("%d", &val);

		//给第 i+1 个节点分配内存空间
		struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
		if(NULL == pNew){
			printf("分配失败,程序终止!\n");
			exit(-1);
		}
		//内存分配成功后
		pNew->data = val;      //新节点赋值
		pTail->pNext = pNew;   //pNew指向的地址给头结点的变量
		pNew->pNext = NULL;    //新节点地址变量给空值
		pTail = pNew;         //又一次使pTai 替换 pNew进行下一次分配创建
	}
	return pHead;
}

void traverseList(struct Node * pHead){
	struct Node * p = pHead->pNext;
	while(NULL != p){
		printf("%d\n", p->data);
		p = p->pNext;
	}
	return;
}


Guess you like

Origin www.cnblogs.com/mqxnongmin/p/10959047.html