#include<iostream>
using namespace std;
struct node {
int data;
node *link;
};
node *head = NULL;
void insert(int data, int n)
{
node *temp = new node();
temp->data = data;
if (n == 1)
{
temp->link = head;
head = temp;
}
else
{
node* ptr = head;
for (int i = 1; i <= n - 1; i++)
ptr = ptr->link;
temp->link = ptr->link;
ptr->link = temp;
}
}
void print()
{
cout << "list is: ";
node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->link;
}
cout << endl;
}
int main()
{
insert(2, 1);
insert(3, 2);
insert(4, 3);
insert(5, 4);
insert(6, 5);
print();
return 0;
}
This is a code to implement insertion in a linked list at nth position. The data and position are being passed from the main position.
I am not getting what is the possible error I have made, it has something to do with the for loop
.
Its not executing, however if i make the following change:
for(int i=0;i<n-2;i++)
it works fine.
答案 0 :(得分:1)
第一个insert(2,1)
工作正常。所以你有这样的链接列表
(2)->NULL
|
head
在第二个插入中,让我们跟随代码
1. else
2. {
3. node* ptr = head;
4. for (int i = 1; i <= n - 1; i++)
5. ptr = ptr->link;
6. temp->link = ptr->link;
7. ptr->link = temp;
8. }
第3行,ptr
指向head
。 n
是2
(2)->NULL
|
head
|
ptr
第4行,1 <= (2-1)
是true
,因为1 == 1
,所以for循环运行一次
第5行,ptr
移动了一步,因此它指向NULL
(2)->NULL
| |
head |
|
ptr
第6行,称为ptr->link
,NULL->link
。所以它在这里崩溃了。
当您执行for(int i=0;i<n-2;i++)
时,n
为2,因此0 < (2-2)
为false
,因此运行正常。注意:仅当按您的示例的顺序进行插入调用时,该功能才有效。如果以错误的顺序调用它们,它将无法正常工作。
将第6行更改为temp->link = ptr;
,也应该在不更改循环的情况下起作用。
答案 1 :(得分:0)
"Inserting a node in nth position in a linked list" :
Use a std::list
rather than rolling your own. Then use std::list::insert.
Also; consider just using a std:: vector
instead. A list is a terrible (pointer chasing, cache miss inducing) data structure to use on modern CPUs. A std::vector
will almost always beat it (regardless of what your textbooks say about theoretical performance).