簡體   English   中英

C ++中鏈表代碼中的分段錯誤

[英]Segmentation fault in linked list code in C++

所以,我試圖在 C++ 上實現這段代碼,它在鏈表的特定位置插入一個元素,但我不斷收到分段錯誤。 我已經將其縮小到主函數中的 l.push(a) 語句,但無法糾正它。

n - 節點數。 然后插入鏈表。 data - 要插入列表的數據。 pos - 要插入數據的位置。

任何有關如何糾正此問題的幫助以及如何避免此類代碼中的分段錯誤的建議將不勝感激:)

//INSERTING ELEMENT AT A SPECIFIC POSITION IN A LINKED LIST - HACKERRANK
#include<iostream>
#include<cstdio>
#include<vector>
#include<limits>
#include<algorithm>
#include<cmath>
using namespace std;

struct Node{
    int data;
    Node* next;
};

struct Linkedlist{
    Node* head;
    Linkedlist(){
        head= NULL;
    }
    void push(int data){
        Node* temp = new Node;
        temp->data = data;
        temp->next = NULL;
        Node* curr = head;
        while(curr->next!=NULL)
            curr= curr->next;
        curr->next = temp;
    }
    void pushpos(int data,int pos){
        Node *curr = head;
        int curr_index = 0;
        while((pos-1)!=curr_index){
            curr=curr->next;
            curr_index++;
        }
        Node *temp = new Node;
        temp->data = data;
        temp->next = curr->next;
        curr->next = temp;

    }
    void print(){
        Node *curr = head;
        while(curr!=NULL){
            cout<<curr->data<<endl;
            curr = curr->next;
        }
    }
};
 
int main(){
    int n,i,a,data,pos;
    Linkedlist l;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>a;
        l.push(a);
    }
    cout<<"pushed";
    cin>>data>>pos;
    l.pushpos(data,pos);
    l.print();  
    return 0;
}


你在這里犯了幾個錯誤。

1.在您的推送 API 中,您沒有檢查 Null。

void push(int data) {
        Node* temp = new Node;
        temp->data = data;
        temp->next = NULL;
        if (head == NULL)
            head = temp;
        else {
            Node* curr = head;
            while (curr->next != NULL)
                curr = curr->next;
            curr->next = temp;
        }
    }
  1. 再次在 pushpos 中,您不會檢查諸如 NULL 之類的失敗條件,以及如果 pos 大於鏈表本身的大小會怎樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM