在链表的第 n 个位置插入一个节点
Inserting a node in nth position in a linked list
#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;
}
这是实现链表第n位插入的代码。数据和位置正在从主位置传递。
我不明白我可能犯了什么错误,这与 for loop
.
有关
它没有执行,但是如果我进行以下更改:
for(int i=0;i<n-2;i++)
它工作正常。
"Inserting a node in nth position in a linked list" :
使用 std::list
而不是自己滚动。然后使用 std::list::insert.
还有;考虑只使用 std:: vector
代替。列表是现代 CPU 上使用的 糟糕 (指针追逐、高速缓存未命中)数据结构。 std::vector
几乎总能打败它(无论您的教科书对理论性能的评价如何)。
第一个 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;
,也应该在不更改循环的情况下工作。
#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;
}
这是实现链表第n位插入的代码。数据和位置正在从主位置传递。
我不明白我可能犯了什么错误,这与 for loop
.
它没有执行,但是如果我进行以下更改:
for(int i=0;i<n-2;i++)
它工作正常。
"Inserting a node in nth position in a linked list" :
使用 std::list
而不是自己滚动。然后使用 std::list::insert.
还有;考虑只使用 std:: vector
代替。列表是现代 CPU 上使用的 糟糕 (指针追逐、高速缓存未命中)数据结构。 std::vector
几乎总能打败它(无论您的教科书对理论性能的评价如何)。
第一个 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;
,也应该在不更改循环的情况下工作。