无法遍历链表

问题描述 投票:0回答:1

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

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

}

c++ linked-list traversal
1个回答
0
投票

您的插入函数应该是:

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

并且当您调用函数时:

insertion_front(&head, 41234);
© www.soinside.com 2019 - 2024. All rights reserved.