在链表的末尾添加一个节点
adding a node at the end of a linked list
我对将新节点添加到链接它的程序有点停滞不前,它应该添加到列表的末尾,但我尽我所能,但仍然有一个解决方案,希望你们中的任何人可以帮助我提前感谢;
这是一段代码
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* head;
void insert(int x);
void numInsert();
void numSearch();
int main()
{
head=NULL;
int x,n;
cout <<"How many number? n";
cin >>n;
for (int i=0; i<n; i++){
cout <<"Enter Number n";
cin >> x;
}
node* newNode;
newNode = new node();
newNode->data=x;
newNode->next=head;
head=newNode;
/*
NewNode->next=NULL;
if (head !=NULL){
NewNode->next=head;
}
else{
head=NewNode;
}*/
int num;
cout<<"what number do you want to insert in the list n";
cin>>num;
node *nNode;
nNode = new node();
nNode->data=num;
nNode->next=NULL;
node *prevNode;
node *currNode;
prevNode=NULL;
currNode=NULL;
{
node* nNode= new node;
nNode->data= num;
nNode->next= NULL;
currNode=NULL; prevNode=NULL;
for(currNode=head; currNode != NULL; currNode= currNode->next)
{
if (newNode->data <= currNode->data)
{
break;
}
prevNode = currNode;
}
newNode->next=prevNode->next;
prevNode->next=newNode;
}
return 0;
}
每当我运行它时,到达一个点并停止工作,请帮助我,作业今天到期,我不知道如何正确解决它
#include <iostream>
using namespace std;
struct node {
int data;
node* next;
};
node* head;
node* tail;
void insert(int x);
void numInsert();
void numSearch();
int main()
{
head=NULL;
tail = NULL;
int x,n;
cout <<"How many number? n";
cin >>n;
for (int i=0; i<n; i++){
cout <<"Enter Number n";
cin >> x;
if(head==NULL){
head = new node();
head->data = x;
head->next = NULL;
tail = head;
}else{
node* newNode;
newNode = new node();
newNode->data=x;
newNode->next = NULL;
tail->next = newNode;
tail = tail->next;
}
}
cout << "Linked List :" << "n";
node* trav = head;
for (int i=0; i<n; i++){
cout << (trav->data) << 'n';
trav = trav->next;
}
int num;
cout<<"what number do you want to insert in the list n";
cin>>num;
if(head==NULL){
head = new node();
head->data = num;
head->next = NULL;
tail = head;
}else{
node* newNode;
newNode = new node();
newNode->data=num;
newNode->next = NULL;
tail->next = newNode;
tail = tail->next;
}
cout << "Linked List :" << "n";
trav = head;
while(trav != NULL){
cout << (trav->data) << 'n';
trav = trav->next;
}
return 0;
}
相关文章:
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 在C++的链表末尾插入一个节点
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++循环链表删除,计数从下一个节点开始
- 如何删除上一个节点?
- 添加一个节点,并在通用树中的两个给定节点之间找到路径成本,其中c 中的儿童列表
- 我试图键入一个函数来在单链表的末尾添加一个节点,但不起作用
- 尝试指向链表中的上一个节点
- 取消下一个节点的空链接列表的头
- 删除最后一个节点,并将尾部更新到最后一个节点
- 计算列表中与线性链接列表中最后一个节点具有相同数据的节点的数量
- 从C++二进制搜索树中删除一个节点(类而非结构)
- 为什么我的原始二叉搜索树被修改,即使我在另一个节点中复制了根节点
- 如何在QT中获取XML文件的最后一个节点
- 交换C 中的第一个和最后一个节点
- 删除链表的每隔一个节点
- 尾部指向最后一个节点
- 使用循环在链接列表的前面插入一个节点