簡體   English   中英

在單鏈列表的后端插入節點

[英]Inserting node at rear end in a singly linked list

我正在編碼在單個LinkedList的最后插入一個節點。 程序正在執行,沒有任何錯誤,但是在輸入第一個數字后運行了無限循環。 我找不到在代碼中提交的邏輯錯誤。 任何幫助將是可觀的:)。

這是代碼和我嘗試過的內容:

#include<bits/stdc++.h>
using namespace std;
struct node{
    int data;
    node* next;
};
node* head = NULL; // empty list
node* temp;
void insert(int x){
    temp = (node*)malloc(sizeof(node));
    temp -> data = x;
    temp -> next = NULL;
    if (head == NULL) head = temp; 
    node* temp1 = head;
    // traversing the list
    while(temp1 -> next != NULL){
    temp1 = temp1 -> next;
    }   
    temp1 -> next = temp;
}
void print(){
    node* iterator = head;
    while(iterator != NULL){
        cout << iterator -> data;
        iterator = iterator -> next;
    }
}
int main(){
    int n, x;
    cout << "how many numbers\n";
    cin >> n;
    for(int i = 0; i < n; i++){
        cout << "enter the value";
        cin >> x;
        insert(x);
        print();
    }
    return 0;
}

我希望輸出是一個鏈表,但是o / p是無限個第一個輸入的數字/數據(在這種情況下為'x')

那么insert函數的邏輯顯然是錯誤的

讓我們一步一步。

首先,您分配節點並將其分配給temp 由於這是C ++,因此應使用new並應使用構造函數,但我們會讓它通過。

然后,由於head等於NULL,因此將head設置為temp

然后將temp1設置為head ,這是因為上一步意味着temp1等於temp

然后循環到temp1指向的最后一個節點。 在這種情況下,您已經在最后一個節點上,因此不會進入循環。

然后將temp1->next設置為temp ,但請記住temp1等於temp (請參見前面的兩個步驟),因此現在您創建了一個循環列表。 這解釋了您的無限循環。

我猜你是要寫這個

if (head == NULL) { head = temp; return; }

也許這

if (head == NULL)
{
    head = temp; 
}
else
{
    ...
}

暫無
暫無

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

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