1、代码
#include<stdio.h>
#include<malloc.h>
//定义结构体
typedef struct LinkNode
{
char data;
struct LinkNode *next;
}LNode,*LinkList,*NodePtr;
//初始化链表,返回头指针
LinkList initLinkList()
{
NodePtr tempHeader = (NodePtr)malloc(sizeof(LNode));
tempHeader->data = '\0';
tempHeader->next = NULL;
return tempHeader;
}
//打印链表
void printList(NodePtr paraHeader)
{
NodePtr p = paraHeader->next;
while (p != NULL)
{
printf("%c", p->data);
p = p->next;
}
printf("\r\n");
}
//添加一个元素
void appendElement(NodePtr paraHeader, char paraChar)
{
NodePtr p,q;
//1、构建一个新结点
q = (NodePtr)malloc(sizeof(LNode));
q->data = paraChar;
q->next = NULL;
//2、找到尾结点
p = paraHeader;
while (p->next != NULL)
{
p = p->next;
}
//3、插入新结点
p->next = q;
}
//插入一个元素到指定位置
void insertElement(NodePtr paraHeader, char paraChar, int paraPosition)
{
NodePtr p, q;
//1、找到插入位置
p = paraHeader;
for (int i = 0; i < paraPosition; i++)
{
p = p->next;
if (p == NULL)
{
printf("The position %d is beyond the scope of the list", paraPosition);
return;
}
}
//2、构建一个新结点
q = (NodePtr)malloc(sizeof(LNode));
q->data = paraChar;
//3、插入
printf("linking\r\n");
q->next = p->next;
p->next = q;
}
//从链表中删除一个元素
void deleteElement(NodePtr paraHeader, char paraChar)
{
NodePtr p, q;
p = paraHeader;
while ((p->next != NULL) && (p->next->data != paraChar))
{
p = p->next;
}
if (p->next == NULL)
{
printf("Cannot delete %c\r\n", paraChar);
return;
}
q = p->next;
p ->next = p ->next->next;
free(q);
}
//测试
void appendInsertDeleteTest()
{
//1、初始化一个空链表
LinkList tempList = initLinkList();
printList(tempList);
//2、增添字符
appendElement(tempList, 'H');
appendElement(tempList, 'e');
appendElement(tempList, 'l');
appendElement(tempList, 'l');
appendElement(tempList, 'o');
appendElement(tempList, '!');
printList(tempList);
//3、删除元素
deleteElement(tempList, 'e');
deleteElement(tempList, 'a');
deleteElement(tempList, 'o');
printList(tempList);
//4、插入元素到指定位置
insertElement(tempList, 'o', 1);
printList(tempList);
}
//地址测试
void basicAddressTest()
{
LNode tempNode1, tempNode2;
tempNode1.data = 4;
tempNode1.next = NULL;
tempNode2.data = 6;
tempNode2.next = NULL;
printf("The first node:%d,%d,%d\r\n", &tempNode1, &tempNode1.data, &tempNode1.next);
printf("The second node:%d,%d,%d\r\n", &tempNode1, &tempNode1.data, &tempNode1.next);
tempNode1.next = &tempNode2;
}
int main()
{
appendInsertDeleteTest();
}
2、运行结果
3、图示
(1)
(2)