我试图制作一个代码,其中给出了10个数字(未分类),我必须使用插入排序对它们进行排序并删除节点。例如,如果10个数字是
50 20 30 10 100 90 80 70 60 40
结果应该是
10 20 30 40 50 60 70 80 90 100
50被删除
10 20 30 40 60 70 80 90 100
20被删除
10 30 40 60 70 80 90 100
删除30 ...
40
因此,节点将按照它们首先给出的顺序删除。 void PrintNode(),callInsertNode(),callDeleteNode()是通过这种方式给出的(其他未发布的那些。我只发布了必要的那些),我试图完成void InsertNode(int v)和void DeleteNode (int v)。
class Node{
public:
int value;
Node *next;
};
class LinkedList{ //Singly Linked List
public:
LinkedList(){
head=NULL;
private:
Node *head;
int *x;
int n;
}
void InsertNode(int v){
cout<<v<<" is inserted"<<endl;
Node* cur=head;
if(cur== NULL || cur->next == NULL) {
return;
}
Node *t1 = cur->next;
while(t1 != NULL) {
int sec_data = t1->value;
int found = 0;
Node *t2 = cur;
while(t2 != t1) {
if(t2->value > t1->value && found == 0) {
sec_data = t2->value;
t2->value = t1->value;
found = 1;
t2 = t2->next;
} else {
if(found == 1) {
int temp = sec_data;
sec_data = t2->value;
t2->value= temp;
}
t2 = t2->next;
}
}
t2->value = sec_data;
t1 = t1->next;
}
void PrintNode(){
Node *cur=head;
while(cur!=0){
cout<<cur->value<<" ";
cur=cur->next;
}
cout<<endl;
}
void CallInsertNode(){
int i;
for(i=0; i<n; i++)
InsertNode(x[i]);
}
void CallDeleteNode(){
int i;
for(i=0; i<n; i++){
DeleteNode(x[i]);
this->PrintNode();
}
}
void DeleteNode(int v){
cout<<v<<" is deleted."<<endl;
Node *cur=head;
Node *previous = head;
Node *delNode=cur;
while(cur!=NULL)
if(cur->value == v)
{
previous->next = delNode->next;
delete delNode;
return;
}
previous = cur;
cur=cur->next;
}
答案 0 :(得分:0)
是的,它对我来说是正确的。只是做一些随机数据的测试,以防我丢失/忽略某些事情。但除此之外(通过代码和干运行)它看起来还不错。