C语言单向链表的实现与操作

最近迷上了C语言,特意借来一本有关C语言算法精解的书籍,书中有不少好代码,借鉴过来分享给大家。

这里有博客中的所有源代码:Github项目地址

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

#define LEN sizeof(struct node)

struct node
{
	int data;
	struct node *next;
};

int main(int argc, char const *argv[]) {
	struct node *p, *pl, *head;

	head = p = (struct node *)malloc(LEN);
	scanf("%d", &p->data);
	/*替代EOF变为输入0的时候终止对链表的输入*/
	while (p->data != 0) {
		pl = p;
		p = (struct node *)malloc(LEN);
		scanf("%d", &p->data);
		pl->next = p;
	}

	p->next = NULL;
	p = head;

	printf("List number is:");

	/*链表中指针指向元素不为空,循环输出链表中的元素*/
	while (p->next != NULL) {
		printf("%d\n", p->data);
		p = p->next;
	}

	printf("%d\n", p->data);
}


上述代码中如有不足,望大家批评指正!

猜你喜欢

转载自blog.csdn.net/shiyipaisizuo/article/details/78993561