C 两个链表中数据节点的数据域为一个字母 ,其中L1包含L2,在L1中找出与L2相等的字串,并将其逆置
//结构体
typedef struct Node {
ElementType data;
struct Node * next;
} LNode, * LinkNode;
//两个链表中数据节点的数据域为一个字母 https://www.ppkao.com/shiti/10246374
Status reverseSubLink(LinkNode *L1, LinkNode L2){
//分两步走,先找出L1中L2的字串
//L1: a b c d e f g h i j k l m n o p q r s
//L2: f g h i j k l m n o p q r
if((*L1) == NULL && L2 == NULL)
return ERR;
//字串找到还要知道它的两个顶点,第一个设为pre最后一个设为p
LinkNode p = (*L1)->next;
LinkNode pre = (*L1);
LinkNode move = L2->next;
//找到子串
while (pre && move) {
//相等的时候,两个并排着往下走
if(move->data == p->data){
p = p->next;
move = move->next;
}//突然发现里面有一个不一样了,那么move就重置,pre和p也从第一个字符串的第二个接着再来
else
{
pre = pre->next;
p = pre->next;
move = L2->next;
}
}
//查找完毕之后,看看L2的子串到底了没有,到底了说明找出来了
//pre是e, p就是s,中间夹得就是需要逆置的子字符串
if(move == NULL){
//现在pre和p就是需要逆置的起始点了,将字串先给temp放着
LinkNode temp = pre->next;
LinkNode t;
//直接在结尾加上最后的链,就相当于把子串在原来的字符串删去
//然后过来一个新的串用头插法的方式将其插入
pre->next = p;
//L1: a b c d e s
//temp: f g h i j k l m n o p q r
//p: s
//pre: e
while (temp != p) {
t = temp;
temp = temp->next;
//头插法
t->next = pre->next;
pre->next = t;
}
//到这里
//pre: e
//t: s
}else{
return ERR;
}
return OK;
}
本文来自博客园,作者:赫凯,转载请注明原文链接:https://www.cnblogs.com/heKaiii/p/15491261.html

浙公网安备 33010602011771号