数据结构示例之由尾部插入新元素的链表

以下为“由尾部插入新元素的链表”的简单示例:

1. 用c语言实现的版本

#include
#include

typedef   char  datatype;
typedef	  struct	node{
	datatype	  data;
	struct 	node  *next;
} listnode;
typedef  listnode  *linklist;
listnode  *p;

/* 创建在尾部插入新元素的链表 */
linklist  creater()
{
	char  ch;
	linklist  head;
	listnode  *p, *r;
	head = r = NULL;/* r为尾指针 */

	printf("请输入字符序列:\n");
	while ((ch = getchar()) != '\n')
	{
		p = (listnode *)malloc(sizeof(listnode));
		p->data = ch;
		if (head == NULL)
		{
			head = r = p; /* head指向第一个插入结点 */
		}
		else
		{
			r->next = p; /* 插入到链表尾部 */
		}
		r = p; /*r指向最新结点,即最后结点*/
	}

	if (r != NULL)
	{
		r->next = NULL; /* 链表尾部结点的后继指针指定为空 */
	}
	return head;
}

void main()
{
	linklist newlist = creater();
	printf("从头结点开始输出链表元素的值:\n");
	do
	{
		printf("%c", newlist->data);
		newlist = newlist->next;
	} while (newlist != NULL);
	printf("\n");
}

运行结果如下图所示:


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