嵌入式菜鸟算法③---链表操作

主要内容:链表头插法和尾差法

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

//typedef int data;
typedef struct node
{
	char data;
	struct node* next;
}linklist;

/* method 1 insert node as first element */ 
linklist* CreateList1()
{
	char ch;
	linklist *head, *p, *q;
	int i = 1;
	head = NULL;
	
	printf("Please input single char:\n");
	scanf("\n%c", &ch);   // if not add \n before %c or add behind it will be some error,i'm not know it yet 
	
	while(ch != '#')
	{
		p = (linklist*)malloc(sizeof(linklist));
		p->data = ch;
		p->next = head;
		head = p;
		printf("already created %d linklist element\n", i);
		q = head;
		while(q != NULL)
		{
			printf("%c ->", q->data);
			q = q->next;
		}
		printf("NULL\n");
		i++;
		printf("Please input %d charactor\n", i);
		scanf("\n%c", &ch);
	}
	return head;
}

/* method 2 insert node for the last element*/
linklist* CreateList2()
{
	char ch;
	linklist *head, *p, *e, *q;
	int i = 1;
	head = NULL;
	e = NULL;
	
	printf("Please input char:\n");
	scanf("\n%c", &ch);  //在 "%c中加一个\n 就可以输入,奇葩·"
	
	while(ch != '#')
	{
		p = (linklist*)malloc(sizeof(linklist));
		p->data = ch;
		
		if (head == NULL)
			head = p;
		else
			e->next = p;
			
		e = p;
		p->next = NULL;
		
		printf("already created %d linklist element\n", i);
		q = head;
		while(q != NULL)
		{
			printf("%c ->", q->data);
			q = q->next;
		}
		printf("NULL\n");
		i++;
		printf("Please input %d charactor\n", i);
		scanf("\n%c", &ch);
	}
	return head;
}
int main()
{
	linklist *p;
	int ch;
	
	while(1)		
	{
		printf("Please select:\n");
		printf("(1)insert element at first position\n");
		printf("(2)insert element at last position\n");
		printf("(3)END\n");
		
		scanf("%d", &ch);
		
		switch(ch)
		{
			case 1:
				p = CreateList1();
				break;
			case 2:
				p = CreateList2();
				break;
			case 3:
				return;
			default:
				return;
		}
	}
	return 0;
}

输出结果:


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。