c语言数据结构单链表的实现
通过c语言实现单链表的建立、初始化、尾插法插入结点、头插法插入结点、数据的查找、删除、在指定位置插入结点、在指定位置删除结点、
打印输出数据、统计单链表的长度等功能。
#include <stdio.h>
#include <stdlib.h>
typedef struct List
{
char x;
struct List * next;
}e;
void setHead(e *l)
{
l->next = NULL;
}
void newList(e *l)
{
int i = 1;
char a;
printf("请输入数据!\n");
while (i)
{
a = getchar();
if (a == '$')
{
i = 0;
}
else
{
while (l->next == NULL)
{
e *l2 = (e *)malloc(sizeof(e));
l2->x = a;
l->next= l2;
l = l2;
l2->next = NULL;
break;
}
}
}
}
void endAdd(e *l,char a)
{
e * l1 = l;
while (1)
{
if (l1->next != 0)
{
l1 = l1->next;
}
else
{
break;
}
}
e *l2 = (e *)malloc(sizeof(e));
l2->x = a;
l1->next = l2;
l2->next = NULL;
}
void headAdd(e *l,char a)
{
e *l2 = (e *)malloc(sizeof(e));
l2->x = a;
l2->next = l->next;
l->next = l2;
}
void printfList(e * l)
{
while (l->next != NULL)
{
l = l->next;
printf("%c\t", l->x);
}
printf("\n");
}
void longList(e *l)
{
int i = 0;
while(l->next)
{
l = l->next;
i++;
}
printf("\n该单链表的长度为:%d\n", i);
}
int deleteList(e * l, int j)
{
e *l2 = NULL;
int i = 0;
while (l->next&& j < i - 1)
{
i++;
l = l->next;
}
if (l->next)
{
l2 = l->next;
l->next = l->next->next;
free(l2);
return 0;
}
return -1;
}
int add(e *l, int j, char a)
{
int i = 0;
e *l1=l;
while (l1->next!=NULL)
{
if (j - 1 == i)
{
e *l2 = (e *)malloc(sizeof(e));
l2->next = l1->next;
l1->next = l2;
l2->x = a;
return 0;
}
i++;
l1 = l1->next;
}
return -1;
}
int findList(e *l, char a)
{
e *l1 = l;
int i = 0;
while (l1->next != NULL)
{
l1 = l1->next;
i++;
if (l1->x == a)
{
return i;
}
}
return -1;
}
int main()
{
e *head = (e *)malloc(sizeof(e));
setHead(head);
newList(head);
longList(head);
printfList(head);
headAdd(head, 's');
longList(head);
printfList(head);
deleteList(head,1);
longList(head);
printfList(head);
add(head, 2, 's');
longList(head);
printfList(head);
int q=findList(head, 's');
if (q > 0)
{
printf("该结点的位置是:%d\n", q);
}
else
{
printf("没有找到该结点\n");
}
system("pause");
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e07929cdf15920ff4af2f8b4c9475d7f.png)