给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。如下实例。
输入:“abbaca”
输出:“ca”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct String{
char data;
struct String *next;
};
int main(){
int i,j,n;
char str[100];
struct String* strs = (struct String*)malloc(sizeof(struct String)),*p;
printf("请输入一个字符串:\n");
scanf("%s",str);
n = strlen(str);
// 将字符串转为链表
for(i=0;i<n;i++){
struct String* s = (struct String*)malloc(sizeof(struct String));
s->data = str[i];
p = strs;
while (p->next != NULL){
p = p->next;
}
p->next = s;
}
//***************************************************核心代码区域***************************************************//
struct String* p1 = strs;
struct String* p2 = strs->next;
while (p2 != NULL && p2->next != NULL){
// 相邻结点相等,删除这两个结点
if(p1->next->data == p2->next->data){
struct String* temp1;
struct String* temp2;
temp1 = p1->next;
temp2 = p2->next;
p1->next = p2->next->next;
free(temp1);
free(temp2);
p1 = strs;
p2 = strs->next;
continue;
}
p1 = p1->next;
p2 = p2->next;
}
// 打印
p1 = strs->next;
while (p1 != NULL){
printf("%c",p1->data);
p1 = p1->next;
}
return 0;
}