头插法建立链表--逆序输出

#include
#include
#include

#define OK 1;
#define ERROR -1;
typedef char elemdata;

typedef struct node {
elemdata data;
struct node *next;
}Lnode,*linklist; //单链表结点类型描述

//创建一个带头结点的单链表(头插法)
Lnode *headcreat()
{
Lnode *h,*p;
elemdata ch;
h = (Lnode*)malloc(sizeof(Lnode));
h->next = NULL;
while((ch = getchar()) != '\n')
{
p = (Lnode*)malloc(sizeof(Lnode));
  p->data = ch;
  p->next = h->next;
  h->next = p;
}

return (h);
}

//取元素
//读取单链表中第i个元素,1<=i<=length(h)
elemdata get(Lnode *h, int i)
{
int j = 1;
Lnode *p;
p = h->next;
while(p && j < i)//移动p,直到p为空,或者j < i
{
  p = p->next;
  j++;
}

if((p != NULL) && j == i)
  return (p->data);
else
  return ERROR;
}

//删除元素
//删除i元素,并返回其值,1<=i<=length(h)  
elemdata delete(Lnode *h, int i)
{
int j = 1;
elemdata e;
Lnode *p, *q;
p = h->next;
while((p->next != NULL)&& j < i-1)
{
  p = p->next;
  j++;
}
if((p->next != NULL) && j == i-1)
{
  q = p->next;
  p->next = q->next;
  e = q->data;
  free(q);
  return e;
}
else
  return ERROR;
}
//插入元素
//第i个元素之前插入一个元素
int insert(Lnode *h, int i, elemdata x)
{
Lnode *p, *s;
p = h->next;
int j = 1;
while(p && j < i - 1)//寻找第i-1个结点
{
  p = p->next;
  j++;
}
if(p && j == i- 1)
{
  s = (Lnode *)malloc(sizeof(Lnode));
  s->next = p->next;
  p->next = s;
  s->data = x;
  return OK;
}
else
  return ERROR;
}

//求链表的长度
int length(Lnode *h)
{
int i = 0;
Lnode *p;
p = h->next;
while(p != NULL)
{
  p = p->next;
  i++;
}
return i;
}
//查找链表中是否存在数据域为x的结点
//若存在返回该结点的指针,否则返回空。
elemdata locate(Lnode *h, elemdata x)
{
Lnode *p;
p = h->next;
while(p&&(p->data != x))
  p = p->next;
if(p)
  return p->data;
else
  return ERROR;
}

//主程序

#include"lklist_1.c"

int main()
{
Lnode* headlist, taillist;
int j = 1, count;
headlist = headcreat();
printf("请输入所创建链表的元素个数:");
scanf("%d", &count);
printf("取单链表中第2个元素:");
printf("%c\n",get(headlist, 2));
printf("删除单链表中第3个元素:");
printf("%c\n",delete(headlist, 3));
printf("在链表中第3个元素之前插入c.\n");
insert(headlist, 3, 'c');
printf("依次输出单链表中的元素:");
for(j = 1; j < count + 1; j++)
{
  printf("%c",get(headlist, j));
}
printf("\n");
printf("链表的长度为:%d\n", length(headlist));
printf("查找链表中是否存在数据域为x的结点:");
if(-1 == locate(headlist, 'x'))
  printf("链表中没有此元素。\n");
else
  printf("%c\n",locate(headlist, 'x'));
return 0;
}

你可能感兴趣的:(C语言)