头插法/尾插法建立线性链表

头插法


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

typedef char ElemType;

typedef struct Node{
	ElemType data;
	struct Node *next;
}Node, *LinkList;

LinkList CreateFromHead()
{
	LinkList L;
	Node *s;
	char c;
	int flag = 1;
	L = (LinkList)malloc(sizeof(Node));
	L->next = NULL;
	while(flag)
	{
		c = getchar();
		if(c != '#')
		{
			s = (Node*)malloc(sizeof(Node));
			s->data = c;
			s->next = L->next;
			L->next = s;
		}
		else
		{
			flag = 0;
		}
	}
	return L;
}

int main()
{
	LinkList L;
	Node *p;
	L = CreateFromHead();
	p = L->next;
	while(p != NULL)
	{
		printf("%c\n",p->data);
		p = p->next;
	}
	return 0;
}



尾插法


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

typedef char ElemType;

typedef struct Node{
	ElemType data;
	struct Node *next;
}Node, *LinkList;

LinkList CreateFromTail()
{
	LinkList L;
	char c;
	Node *r, *s;
	int flag = 1;
	L = (Node*)malloc(sizeof(Node));
	L->next = NULL;
	r = L;
	while(flag)
	{
		c = getchar();
		if(c != '#')
		{
			s = (Node *)malloc(sizeof(Node));
			s->data = c;
			r->next = s;
			r = s;
		}
		else
		{
			flag = 0;
			r->next = NULL;
		}
	}
	return L;
}

int main()
{
	LinkList L;
	Node *p;
	L = CreateFromTail();
	p = L->next;
	while(p != NULL)
	{
		printf("%c\n",p->data);
		p = p->next;
	}
	return 0;
}


posted @ 2013-03-06 15:41  N3verL4nd  阅读(280)  评论(0编辑  收藏  举报