#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;
//创建了一个节点q
q = (NodePtr)malloc(sizeof(LNode));
q->data = paraChar;
q->next = NULL;
//把q插到p表后面
p = paraHeader;
while (p->next != NULL) {
p = p->next;
}
p->next = q;
}
//在表的某个位置插入一个节点
void insertElement(NodePtr paraHeader, char paraChar, int paraPosition) {
NodePtr p, q;
//判断要求位置是否大于表长
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;
}
}
//创建节点q
q = (NodePtr)malloc(sizeof(LNode));
q->data = paraChar;
//插入
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() {
LinkList tempList = initLinkList();
printList(tempList);
appendElement(tempList, 'H');
appendElement(tempList, 'e');
appendElement(tempList, 'l');
appendElement(tempList, 'l');
appendElement(tempList, 'o');
appendElement(tempList, '!');
printList(tempList);
deleteElement(tempList, 'e');
deleteElement(tempList, 'a');
deleteElement(tempList, 'o');
printList(tempList);
insertElement(tempList, 'o', 1);
printList(tempList);
}
void basicAddressTest() {
LNode tempNode1, tempNode2;
tempNode1.data = 4;
tempNode2.next = NULL;
tempNode1.data = 6;
tempNode2.data = NULL;
printf("The first node: %d, %d, %d\r\n", &tempNode1, &tempNode1.data, &tempNode1.next);
printf("The second node: %d, %d, %d\r\n", &tempNode2, &tempNode2.data, &tempNode2.next);
tempNode1.next = &tempNode2;
}
int main() {
appendInsertDeleteTest();
}
运行结果
分析及体会
该代码可以实现C语言单链表的创建、打印、元素的插入和删除等功能。本次学习加深了我对单链表的理解。单链表具有动态分配内存、扩展性强、插入和删除效率高等优点,但也存在访问元素效率低、需要额外空间存储指针、容易出现内存泄漏以及无法直接获取链表长度等缺点。