码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-10 00:33:45      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:算法   数据结构   链表   

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

#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;
}

输出结果:

bubuko.com,布布扣

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

标签:算法   数据结构   链表   

原文地址:http://blog.csdn.net/human_evolution/article/details/41833453

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!