本段代码简单实现了双向链表的基本操作,包括初始化链表、插入元素、删除元素、打印链表内容以及一个基础的地址测试
双向链表的初始化:
initLinkList函数创建一个头节点,数据域为空字符,前驱和后继指针都设置为NULL,表示一个空的双向链表。
//链表初始化
DLNodePtr initLinkList() {
DLNodePtr tempHeader = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
tempHeader->data = '\0';
tempHeader->previous = NULL;
tempHeader->next = NULL;
return tempHeader;
}
打印链表元素:
printList函数遍历链表并打印每个节点的数据域,用于查看链表当前的内容
//打印链表中的内容
void printList(DLNodePtr paraHeader) {
DLNodePtr p = paraHeader->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\r\n");
}
插入元素:
insertElement函数在链表的指定位置插入一个新的元素。首先找到插入位置的前一个节点,然后创建新节点并调整相应的指针,以将新节点插入到链表中。
//在链表中插入元素
void insertElement(DLNodePtr paraHeader, char paraChar, int paraPosition) {
DLNodePtr p, q, r;
p = paraHeader;
//将p移动到插入位置的前面
for (int i = 0; i < paraPosition; i++) {
p = p->next;
if (p == NULL) {
printf("The position % d is beyond the scope of the list.\n",paraPosition);
return;
}
}
//创建一个新的节点
q = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
q->data = paraChar;
//将新节点的前后与链表连接起来
r = p->next;
q->next = p->next;
q->previous = p;
if (r != NULL) {
r->previous = q;
}
}
删除元素:
deleteElement函数从链表中删除指定的元素。首先找到该元素的前一个节点,然后调整指针以从链表中移除该元素,并释放其内存。
//删除链表中的指定元素
void deleteElement(DLNodePtr paraHeader, char paraChar) {
DLNodePtr p, q, r;
p = paraHeader;
//将p移动到目标的前一个
while ((p->next != NULL) && (p->next->data != paraChar)) {
p = p->next;
}
if (p->next == NULL) {
printf("The char %c does not exist.\r\n", paraChar);
return;
}
//将删除目标的前一个与后一个连接起来,并将删除目标的空间释放掉
q = p->next;
r = q->next;
p->next = r;
if (r != NULL) {
r->previous = p;
}
free(q);
}
测试函数:
- insertDeleteTest函数测试了插入和删除操作,首先创建一个空链表,然后插入几个元素,接着删除几个元素,最后再插入一个元素,每步操作后都打印链表的内容,以展示操作的结果。
- basicAddressTest函数展示了如何通过地址访问节点的数据域和指针域,以及如何修改节点的指针以连接不同的节点。
void insertDeleteTest(){ DLNodePtr tempList = initLinkList(); printList(tempList); insertElement(tempList, 'H', 0); insertElement(tempList, 'e', 1); insertElement(tempList, 'l', 2); insertElement(tempList, 'l', 3); insertElement(tempList, 'o', 4); insertElement(tempList, '!', 5); printList(tempList); deleteElement(tempList, 'e'); deleteElement(tempList, 'a'); deleteElement(tempList, 'o'); printList(tempList); insertElement(tempList, 'o', 1); printList(tempList); } void basicAddressTest() { DLNode 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", &tempNode2, &tempNode2.data, &tempNode2.next); tempNode1.next = &tempNode2; }
void main() { insertDeleteTest(); basicAddressTest(); }
该段代码运行结果如下: