【问题标题】:can not traverse a linked list不能遍历链表
【发布时间】:2019-12-02 17:23:47
【问题描述】:

我是链表的新手。最近我创建了一个链表并尝试对其进行一些操作,如插入、删除等。但是我没有遍历链表。我猜头指针在插入过程中会发生变化。我已经多次遇到过这种类型的问题。帮我弄清楚。

#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 ;

}

【问题讨论】:

  • 这能回答你的问题吗? Linked list in C , Can't insert and display node
  • void deletion (node* head , int n) - 您试图在声明temp 中引用未初始化的指针while(temp-&gt;data != n) - 这是未定义的行为..
  • void insertion_front (node* head , int n) 和公司。应该是void insertion_front (node*&amp; head , int n)

标签: c++ linked-list traversal


【解决方案1】:

你的插入函数应该是:

void insertion_front(node** head, int n)
{
    node* temp = new node();
    temp->data = n;
    temp->next = *head;
    *head = temp;
}

当你调用函数时:

insertion_front(&head, 41234);

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2013-10-14
    • 2022-01-06
    相关资源
    最近更新 更多