在链表的末尾插入元素
inserting element at the end of linked list
我试图在链表的末尾插入元素,但while循环不终止。我不明白为什么会发生这种事。这是我的代码。
我在main()函数中调用这个函数。
struct node{
int data;
struct node* link;
};
struct node * head;
void insert_last(int element){
struct node * temp = (node*)malloc(sizeof(struct node));
temp->data = element;
temp->link = NULL;
if(head==NULL){
head = temp;
}
struct node * temp1 = head;
while(temp1->link!=NULL){
temp1 = temp1->link;
}
temp1->link = temp;
}
下面是主要的方法:
int main()
{
head = NULL;
printf("Enter the no. of nodes or elements you want to make linked list of. ");
int n;
scanf("%d",&n);
int element = 0;
for(int i = 0; i<n; i++){
printf("Enter the elementn");
scanf("%d",&element);
insert_last(element);
std::cout<<"Element insertednn";
}
//print_recursive(head);
print();
}
很简单。
if(head==NULL){
head = temp;
}
在这种情况下,你已经完成了你正在做的事情。继续下去,temp1
就变成了temp
。然后temp1->link = temp;
使这个节点指向自己。第二次插入将永远不会找到结束,因为您的列表现在是循环的,while(temp1->link!=NULL)
将永远不会结束。
你应该做的就是把return;
.
if(head==NULL){
head = temp;
return;
}
相关文章:
- 如何在向量数组中插入元素?
- 有没有更快的方法可以在 std::vector 中插入元素
- 映射C++按值排序和插入元素
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 当索引位于末尾和空数组时,向数组插入元素时出现问题
- 在 QSet 中插入元素<QString>并检索 ,删除 QSet 的最后一项
- C++ 在列表末尾插入元素的列表的 STL 向量
- 插入元素后矢量容量增加
- 如何在 c++ 集中插入元素,直到按下 Enter 键
- C++向量插入元素
- 有没有办法在unordered_map的某个位置插入元素
- 重新插入元素可以"re-validate"迭代器吗?
- 内部源代码 - 在链接列表实现中插入元素上的删除会破坏整个应用程序
- 在链表中插入元素
- stl 中是否有任何数据结构可以在 O(1) 或 O(log n) 中插入元素,我可以在其上编写自己的bin_searc
- 如何在将数据结构插入元素后继续迭代数据结构
- 有没有一种方法可以在std::向量的特定位置重复插入元素
- 在向量 (C++) 中保留插入元素的地址
- 插入元素后Unordered_map变空,我做错了什么
- 循环a std :: unordered_map,序列始终是i插入元素的序列