C 兩個連結串列中資料節點的資料域為一個字母 ,其中L1包含L2,在L1中找出與L2相等的字串,並將其逆置
阿新 • • 發佈:2018-11-01
//結構體
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;
}