要用malloc函数和单链表insert,还有要怎么证明这个插入函数在整个管理系统中是正确的?求大佬解答!拜托啦!!!
插入函数
void Insert()
{
cout << "输入要插入的序号为" << endl;
node* p = new node;
cin >> p->data;
p->next = NULL;
cout << "输入在哪个序号前插入" << endl;
int t;
cin >> t;
node* q = head->next, * o = head;//o记录q的前一个结点
while(q)
{
if(q->data!=t)
{
o = o->next;
q = q->next;
}
else
{
p->next = q;
o->next = p;
break;
}
}
if(q==NULL)cout << "序号输入有误" << endl;
else
{
cout << "插入后结果如下" << endl;
for (node* p = head->next; p; p = p->next)
cout << p->data<<'\t';
cout << endl;
}
}
完整验证代码
#include<iostream>
using namespace std;
typedef struct node
{
int data;
node* next;
};
class List
{
private:
node* head, * last;
public:
List()//初始化
{
head = new node;
head->next = NULL;
last = head;
}
void CreateList()//链表创建
{
cout << "节点数" << endl;
int n;
cin >> n;
cout << "输入结点序号" << endl;
for (int i = 0; i < n; ++i)
{
node* p = new node;
cin >> p->data;
//尾插法
last->next = p;
last = p;
}
last->next = NULL;
}
void OutCome()
{
cout << "链表数据如下" << endl;
for (node* p = head->next; p; p = p->next)
cout << p->data << '\t';
cout << endl;
}
void Insert()
{
cout << "输入要插入的序号为" << endl;
node* p = new node;
cin >> p->data;
p->next = NULL;
cout << "输入在哪个序号前插入" << endl;
int t;
cin >> t;
node* q = head->next, * o = head;//o记录q的前一个结点
while(q)
{
if(q->data!=t)
{
o = o->next;
q = q->next;
}
else
{
p->next = q;
o->next = p;
break;
}
}
if(q==NULL)cout << "序号输入有误" << endl;
else
{
cout << "插入后结果如下" << endl;
for (node* p = head->next; p; p = p->next)
cout << p->data<<'\t';
cout << endl;
}
}
};
int main()
{
List l;
l.CreateList();
l.OutCome();
l.Insert();
}
楼上回答我认可