#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;
}
原文地址:http://blog.csdn.net/human_evolution/article/details/41833453