因此,在我的链表列表程序中,我想要它做的是要求用户输入多少个数字,然后输入数字,然后添加这些数字数字在列表的末尾。然后,它将打印列表。之后,用户将选择列表中元素的位置来删除,列表将再次被打印。在列表末尾插入一个整数并在第n个位置删除
#include <iostream>
using namespace std;
struct Node{
int data;
Node* link;
};
Node* head;
void Insert(int data){ //insert an integer at the end of the list
Node* temp = new Node();
Node* temp2 = new Node();
temp->data = data;
temp->link = NULL;
if(head = NULL){
head = temp;
return;
}
temp2 = head;
while(temp2->link != NULL){
temp2 = temp2->link;
}
temp2->link = temp;
}
void Delete(int n){ //delete an integer at nth position
Node* temp1 = new Node();
temp1 = head;
if(n == 1){ //if the first node is to be deleted
head = temp1->link; //now head points to second node
delete temp1; //delete first node
return;
}
for(int i = 0; i < n-2; i++){
temp1 = temp1->link; //temp1 points to (n-1)th node
}
Node* temp2 = temp1->link; //temp2 points to nth node
temp1->link = temp2->link; // pointing to (n+1)th node
delete temp2; //deleting nth node
}
void Print(){ //print out the list
Node* printNode = head;
cout << "List: ";
while(printNode != NULL){
cout << printNode->data;
cout << " ";
printNode = printNode->link;
}
cout << "\n";
}
int main(){
int x, count, n;
head = NULL; //start with an empty list
cout << "How many numbers? " << endl;
cin >> count;
for(int i = 0; i < count; i++){
cout << "Enter number: ";
cin >> x;
Insert(x);
}
Print();
cout << "Enter position to delete: ";
cin >> n;
Delete(n);
Print();
return 0;
}
接受第一个数字后,程序停止工作。我可以知道我在哪里做错了代码,我能做些什么来使代码更有效率?提前致谢。
只有掠过代码当前'如果(head = NULL)'应该是'if(head == NULL)'。不知道这是否解决了整个问题,但它是一个开始 – tomasbasham
@tomasbasham这是一个很大的facepalm我现在已经修复了。 – nisyedlah
没问题,我可以指出,保存一个引用到链表的尾部会更有效率,而不是有t o每次插入数字时都要穿过它 – tomasbasham