删除函数修改如下,供参考:
bool Delete_L(SLinkString &S, char ch)
{
SLinkString p = S->next, q = S, m = NULL;
while (p){
if (p->str == ch){
m = p;
p = p->next;
q->next = p;
free(m);
}
else{
q = p;
p = p->next;
}
}
return true;
}
#include <stdio.h>
#include <stdlib.h>
struct SLinkString {
char str;
SLinkString *next;
};
bool Delete_L(SLinkString &S) {
SLinkString *prev = NULL;
SLinkString *curr = &S;
while (curr != NULL) {
if (curr->str == 'a') {
if (prev == NULL) {
// Removing the first node
S = *(S.next);
free(curr);
curr = &S;
} else {
// Removing a non-first node
prev->next = curr->next;
free(curr);
curr = prev->next;
}
} else {
prev = curr;
curr = curr->next;
}
}
return true;
}
int main() {
// Create a sample list
SLinkString *head = (SLinkString *)malloc(sizeof(SLinkString));
head->str = 'b';
SLinkString *second = (SLinkString *)malloc(sizeof(SLinkString));
second->str = 'a';
head->next = second;
SLinkString *third = (SLinkString *)malloc(sizeof(SLinkString));
third->str = 'c';
second->next = third;
SLinkString *fourth = (SLinkString *)malloc(sizeof(SLinkString));
fourth->str = 'a';
third->next = fourth;
fourth->next = NULL;
// Print the original list
printf("Original List: ");
SLinkString *curr = head;
while (curr != NULL) {
printf("%c ", curr->str);
curr = curr->next;
}
printf("\n");
// Delete all 'a' nodes
Delete_L(*head);
// Print the modified list
printf("Modified List: ");
curr = head;
while (curr != NULL) {
printf("%c ", curr->str);
curr = curr->next;
}
printf("\n");
return 0;
}
输入在第一行给出一个正整数N(≤104)。随后 N 行,每行给出一个玩家的名字(由不超过8个英文字母组成的字符串)和其猜的正整数(≤ 100)。
void ListReverse_L(LinkList &L)
{
if(L==NULL||L->next==NULL)
return; //为空或只有头结点
List l=L->next,p=l->next;
l->next=nullptr;
while(p)
{
List q=p->next;
p->next=l->next;
l->next=p;
p=q;
}
return;
}
简单的就地逆置,知道链表的基本操作都会。这里用了一个技巧,就是不需要新开头结点,把原头结点的next节点作为新的头结点。