1.代码:
#include <stdio.h>
#include <malloc.h>
/**
* 双向链表的整数。键是字符。
*/
typedef struct DoubleLinkedNode {
char data;
struct DoubleLinkedNode* previous;
struct DoubleLinkedNode* next;
} DLNode, * DLNodePtr;
/**
* 使用头部初始化列表。
* @return 指向头部的指针。
*/
DLNodePtr initLinkList() {
DLNodePtr tempHeader = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
tempHeader->data = '\0';
tempHeader->previous = NULL;
tempHeader->next = NULL;
return tempHeader;
}
/**
* 打印列表。
* @param paraHeader 列表的头部。
*/
void printList(DLNodePtr paraHeader) {
DLNodePtr p = paraHeader->next;
while (p != NULL) {
printf("%c", p->data);
p = p->next;
}
printf("\r\n");
}
/**
* 在给定位置插入一个元素。
* @param paraHeader 列表的头部。
* @param paraChar 给定的字符。
* @param paraPosition 给定的位置。
*/
void insertElement(DLNodePtr paraHeader, char paraChar, int paraPosition) {
DLNodePtr p, q, r;
// 第1步。搜索到位置。
p = paraHeader;
for (int i = 0; i < paraPosition; i++) {
p = p->next;
if (p == NULL) {
printf("位置 %d 超出了列表的范围。", paraPosition);
return;
}
}
// 第2步。构造一个新节点。
q = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
q->data = paraChar;
// 第3步。现在链接。
r = p->next;
q->next = p->next;
q->previous = p;
p->next = q;
if (r != NULL) {
r->previous = q;
}
}
/**
* 从列表中删除一个元素。
* @param paraHeader 列表的头部。
* @param paraChar 给定的字符。
*/
void deleteElement(DLNodePtr paraHeader, char paraChar) {
DLNodePtr p, q, r;
p = paraHeader;
// 第1步。定位。
while ((p->next != NULL) && (p->next->data != paraChar)) {
p = p->next;
}
// 第2步。错误检查。
if (p->next == NULL) {
printf("字符 '%c' 不存在。\r\n", paraChar);
return;
}
// 第3步。更改链接。
q = p->next;
r = q->next;
p->next = r;
if (r != NULL) {
r->previous = p;
}
// 第4步。释放空间。
free(q);
}
/**
* 单元测试。
*/
void insertDeleteTest() {
// 第1步。初始化一个空列表。
DLNodePtr tempList = initLinkList();
printList(tempList);
// 第2步。添加一些字符。
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);
// 第3步。删除一些字符(第一次出现的)。
deleteElement(tempList, 'e');
deleteElement(tempList, 'a');
deleteElement(tempList, 'o');
printList(tempList);
// 第4步。插入到给定位置。
insertElement(tempList, 'o', 1);
printList(tempList);
}
/**
* 地址测试:超出书本。
*/
void basicAddressTest() {
DLNode tempNode1, tempNode2;
tempNode1.data = 4;
tempNode1.next = NULL;
tempNode2.data = 6;
tempNode2.next = NULL;
printf("第一个节点:%d, %d, %d\r\n",
&tempNode1, &tempNode1.data, &tempNode1.next);
printf("第二个节点:%d, %d, %d\r\n",
&tempNode2, &tempNode2.data, &tempNode2.next);
tempNode1.next = &tempNode2;
}
/**
* 程序入口。
*/
void main() {
insertDeleteTest();
basicAddressTest();
return;
}
2.运行实例: