-
Notifications
You must be signed in to change notification settings - Fork 0
/
test26.cpp
97 lines (87 loc) · 1.75 KB
/
test26.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<algorithm>
#include<ctype.h>
using namespace std;
struct Node {
char val;
Node* next;
Node(char n = ' ', Node* next_ = nullptr) :
val(n), next(next_) {}
};
void addNode(Node* head, char n)
{
Node* p = head;
Node* newNode = new Node{ n, nullptr };
while (p->next)
{
p = p->next;
}
newNode->val = n;
newNode->next = nullptr;
p->next = newNode;
}
Node* crateList(string& s)
{
Node* list = new Node{ -1, nullptr };
for (int i = 0; i < s.size(); i++)
{
addNode(list, s[i]);
}
return list;
}
void printNode(Node* head)
{
if (head==nullptr) return;
Node* p = head->next;
while (p)
{
std::cout << p->val << ' ';
p = p->next;
}
std::cout << endl;
}
string list_to_string(Node* l)
{
string s;
l = l->next;
while (l)
{
s += l->val;
l = l->next;
}
return s;
}
Node* string_to_list(string& s)
{
Node* list = new Node{ -1, nullptr };
for (int i = 0; i < s.size(); i++)
{
addNode(list, s[i]);
}
return list;
}
string reverseFirstMatch(string s, string t) {
if (s.empty() || t.empty()) {
return s;
}
int pos = s.find(t);
if (pos != string::npos) {
reverse(s.begin() + pos, s.begin() + pos + t.length());
}
return s;
}
int main() {
string sString = "hello_world";
string tString = "lo_wor";
Node* sHead = crateList(sString);
Node* tHead = crateList(tString);
printNode(sHead);
printNode(tHead);
string s = list_to_string(sHead);
string t = list_to_string(tHead);
string ans = reverseFirstMatch(s, t);
sHead = crateList(ans);
printNode(sHead);
}