#include<iostream>
#include<string>
using namespace std;
//子链表存放数据
struct Slist {
char data;
Slist* next;
};
//父链表存放连表名和子链表
struct Dlist {
string data; //定义链表名字
Slist* head; //将子链表插入父链表数据域
Dlist* next;
};
//初始化父链表
Dlist* initdlist() {
Dlist* head = new Dlist;
head->data = "value";
head->head = NULL;
head->next = NULL;
return head;
}
//头插法插入父链表数据
Dlist* headInsert(Dlist* Head, string data, Slist* head) {
Dlist* node = new Dlist;
node->data = data;
node->head = head;
node->next = Head->next;
Head->next = node;
return Head;
}
//子链表的初始化
Slist* initslist() {
Slist* head = new Slist;
head->data = 0;
head->next = NULL;
return head;
}
//子链表插入数据
Slist* createslist(Slist* head, int n) {
Slist* pre = head;
cout << "输入" << n << "个字符:";
for (int i = 0; i < n; i++)
{
Slist* p = new Slist;
cin >> p->data; //新节点的数据域填数据
pre->next = p; //老结点的next指针指向新节点
pre = p; //让新节点赋值给老结点 形成一次循环
pre->next = NULL; //让最后一个新生成的结点指向空 变成尾结点
}
return head;
}
//求父链表长度
int Dlength(Dlist* head) {
Dlist* p = head->next;
int count = 0;
while (p != NULL) {
count++;
p = p->next;
}
return count;
}
//求子节点的长度
int Slength(Slist* head) {
Slist* p = head->next;
int count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
//查找父节点
void Dfind(Dlist* head, string n)
{
Dlist* p = head->next; //父链表首元节点
Slist* q = p->head; //子链表头结点
while (p != NULL) {
if (p->data == n) {
cout << p->data << ",";
while (q->next != NULL) {
cout << q->data;
q = q->next;
}
}
p = p->next;
}
}
int main() {
Slist* p = initslist();
Dlist* q = initdlist();
string name;
while (1) {
cin >> name;
if (name == "createlist") {
string a;
int n;
cout << "请输入链表名字:";
cin >> a;
cout << "请输入结点个数:";
cin >> n;
createslist(p, n);
headInsert(q, a, p);
cout << "插入成功!" << endl;
}if (name == "Dfind") {
string a;
cout << "输入查找的链表名字:";
cin >> a;
Dfind(q, a);
}
if (name == "0") {
delete p, q;
break;
}
}
return 0;
}
//遍历的结果不是相应对应的链表 而是我新建的链表
你Dfind函数的q指针始终指向了新建链表的头结点,你应该在循环内部不断把p置为q的头结点
说反了,是把q指向p的head
哇哦谢谢大神!!!