在单链表的后端插入节点
Inserting node at rear end in a singly linked list
我正在编写代码以在单个 LinkedList 的末尾插入一个节点。程序正在执行,没有任何错误,但在输入第一个数字后 运行 出现无限循环。我在代码中找不到我犯的逻辑错误。任何帮助都将不胜感激:)。
这是代码和我试过的内容:
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
node* head = NULL; // empty list
node* temp;
void insert(int x){
temp = (node*)malloc(sizeof(node));
temp -> data = x;
temp -> next = NULL;
if (head == NULL) head = temp;
node* temp1 = head;
// traversing the list
while(temp1 -> next != NULL){
temp1 = temp1 -> next;
}
temp1 -> next = temp;
}
void print(){
node* iterator = head;
while(iterator != NULL){
cout << iterator -> data;
iterator = iterator -> next;
}
}
int main(){
int n, x;
cout << "how many numbers\n";
cin >> n;
for(int i = 0; i < n; i++){
cout << "enter the value";
cin >> x;
insert(x);
print();
}
return 0;
}
我希望输出是一个链表,但 o/p 是第一个输入的无穷多个 number/data(在本例中为 'x')
那么insert
函数的逻辑显然是错误的
让我们通过它。
首先分配节点并将其分配给temp
。由于这是 C++,您应该使用 new 并且您应该使用构造函数,但我们会让它通过。
然后因为 head
等于 NULL 你设置 head
到 temp
.
然后将 temp1
设置为 head
,因为上一步意味着 temp1
等于 temp
。
然后循环到temp1
指向的最后一个节点。在这种情况下,您已经在最后一个节点,因此不会进入循环。
然后您将 temp1->next
设置为 temp
,但请记住 temp1
等于 temp
,(请参阅前面的两个步骤),所以现在您已经创建了一个循环列表。这解释了你的无限循环。
我猜你是想写这个
if (head == NULL) { head = temp; return; }
或者这个
if (head == NULL)
{
head = temp;
}
else
{
...
}
我正在编写代码以在单个 LinkedList 的末尾插入一个节点。程序正在执行,没有任何错误,但在输入第一个数字后 运行 出现无限循环。我在代码中找不到我犯的逻辑错误。任何帮助都将不胜感激:)。
这是代码和我试过的内容:
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
node* head = NULL; // empty list
node* temp;
void insert(int x){
temp = (node*)malloc(sizeof(node));
temp -> data = x;
temp -> next = NULL;
if (head == NULL) head = temp;
node* temp1 = head;
// traversing the list
while(temp1 -> next != NULL){
temp1 = temp1 -> next;
}
temp1 -> next = temp;
}
void print(){
node* iterator = head;
while(iterator != NULL){
cout << iterator -> data;
iterator = iterator -> next;
}
}
int main(){
int n, x;
cout << "how many numbers\n";
cin >> n;
for(int i = 0; i < n; i++){
cout << "enter the value";
cin >> x;
insert(x);
print();
}
return 0;
}
我希望输出是一个链表,但 o/p 是第一个输入的无穷多个 number/data(在本例中为 'x')
那么insert
函数的逻辑显然是错误的
让我们通过它。
首先分配节点并将其分配给temp
。由于这是 C++,您应该使用 new 并且您应该使用构造函数,但我们会让它通过。
然后因为 head
等于 NULL 你设置 head
到 temp
.
然后将 temp1
设置为 head
,因为上一步意味着 temp1
等于 temp
。
然后循环到temp1
指向的最后一个节点。在这种情况下,您已经在最后一个节点,因此不会进入循环。
然后您将 temp1->next
设置为 temp
,但请记住 temp1
等于 temp
,(请参阅前面的两个步骤),所以现在您已经创建了一个循环列表。这解释了你的无限循环。
我猜你是想写这个
if (head == NULL) { head = temp; return; }
或者这个
if (head == NULL)
{
head = temp;
}
else
{
...
}