#include #include struct Node { char c; // 大写 or 小写 struct Node *prev; struct Node *next; struct Node *same; // 相同的类型的下一个结点 }; // reverse string struct List { int count; struct Node *head; struct Node *lower; // 最近一个小写 struct Node *upper; // 最近一个大写 }; struct Node *createNode(char c) { struct Node *node = malloc(sizeof(struct Node)); if (node == NULL) { exit(0); } node->c = c; node->prev = NULL; node->next = NULL; node->same = NULL; return node; } void insertAtHead(struct List *list, char c) { struct Node *node = createNode(c); if (c == 'm' || c == 'M') { return; } list->count = list->count + 1; if (list->head != NULL) { // 链表不为空 node->next = list->head; list->head->prev = node; list->head = node; } else { // 链表为空 list->head = node; } if (c >= 'a' && c <= 'z') { // 小写 node->same = list->lower; list->lower = node; } else { // 大写 node->same = list->upper; list->upper = node; } } void deleteNode(struct List *list, int Upper) { if (list->count == 0) { return; } struct Node *del_node; // 需要删除的结点 if (Upper) { del_node = list->upper; } else { del_node = list->lower; } if (del_node != NULL) { if (del_node->prev != NULL) { // 不是头结点 del_node->prev->next = del_node->next; if (del_node->next != NULL) { del_node->next->prev = del_node->prev; } } else { list->head = del_node->next; if (list->head != NULL) { list->head->prev = NULL; } } if (Upper) { list->upper = del_node->same; } else { list->lower = del_node->same; } list->count = list->count - 1; free(del_node); } } void displayListKofList(struct List *list, int k) { struct Node *iter = list->head; char *p = malloc(k + 1); for (int i = 0; i < k; i++) { if (iter) { *(p + k - i - 1) = iter->c; iter = iter->next; } } *(p + k) = '\0'; printf("%s", p); } int main() { struct List list; list.head = NULL; list.lower = NULL; list.upper = NULL; list.count = 0; int q; scanf("%d", &q); getchar(); for (int i = 0; i < q; i++) { char c; int newline = 1; while ((c=getchar())!= '\n') { if (c == '?' && newline == 1) { // 如果是查询 int k; scanf("%d", &k); displayListKofList(&list, k); } else { if (c == 'm') { deleteNode(&list, 0); } else if (c == 'M') { deleteNode(&list, 1); } else { insertAtHead(&list, c); } } newline = 0; } } }