c++ - 不能遍历链表
问题描述
我是链表的新手。最近我创建了一个链表并尝试对其进行一些操作,例如插入,删除等。但是我没有遍历链表。我猜头指针在插入过程中会发生变化。我已经多次遇到过这种类型的问题。帮我弄清楚。
#include<bits/stdc++.h>
using namespace std ;
struct node
{
int data ;
struct node* next ;
};
void insertion_end( node* head , int n)
{
node* temp = new node() ;
temp->data = n ;
temp->next = nullptr ;
node* last = head ;
if(head == nullptr)
{
head =temp ;
}
else
{
while ( last != nullptr)
{
last = last->next ;
}
last = temp ;
}
}
void insertion_front (node* head , int n)
{
node* temp = new node();
temp->data = n ;
temp->next = head ;
head = temp ;
}
void deletion (node* head , int n)
{
node* temp ;
node* temp2 ;
while(temp->data != n)
{
temp = temp->next ;
}
if(temp->data != n)
{
cout<< "Not found!" <<"\n" ;
}
temp2 = temp ;
temp = temp->next ;
free(temp2) ;
}
void traverse(node* head)
{
node* temp = head ;
while ( temp->next != nullptr)
{
cout<< " "<< temp->data << "\n" ;
temp =temp->next ;
}
}
int main()
{
cin.tie(NULL);
cout.tie(NULL);
node* head = new node();
head->next = nullptr ;
insertion_end(head , 10);
insertion_end(head , 5463);
insertion_end(head , 474);
insertion_end(head , 5475);
insertion_end(head , 457);
insertion_end(head , 3575);
insertion_front(head , 41234);
insertion_front(head , 68976);
insertion_front(head , 23);
insertion_front(head , 57);
deletion(head , 68976);
traverse( head );
return 0 ;
}
解决方案
您的插入功能应该是:
void insertion_front(node** head, int n)
{
node* temp = new node();
temp->data = n;
temp->next = *head;
*head = temp;
}
当您调用该函数时:
insertion_front(&head, 41234);
推荐阅读
- javascript - 基于条件或重用结构的不同 Html-Tag
- javascript - 使用 JavaScript 合并两个 HTML 行
- html - wordpress 将 div 对齐到中心
- c++ - 在 C++ 中,如果复制一个对象是可能的,但非常昂贵并且通常是一个坏主意,您是否仍然应该使用复制构造函数来实现复制?
- go - 如何修复 Golang 中单值上下文错误的多个值?
- android - 我可以使用 SupportSQLiteOpenHelper 在内部目录或资产文件夹中打开数据库吗?
- javascript - Force Knockout 计算以在替换 observable 内部后重新评估
- javascript - 如何使用 JavaScript 将 JSON 中的 PHP 时间戳转换为日期和时间
- php - 将 html 输入作为 php 的变量
- git - 如何修复 git-lfs 服务器(gitlab)上损坏的文件?