[英]implementing a linked list and it doesn't produce output
我正在實現一個鏈接列表,但它不顯示任何輸出。
實現一個有 4 個元素的鏈表,並制作函數 insert 和 insertathead 和 display。
#include <bits/stdc++.h>
using namespace std;
// class node to make node element.
class node
{
public:
int data;
node *next;
node{
}
// constructor
node(int val)
{
data = val;
next = NULL;
}
// function to insert element at head.
void insertAthead(node *&head, int val)
{
node *n = new node(val);
n->next = head;
head = n;
return;
}
// function to insert in linked list.
void insert(node *head, int val)
{
node *temp = head;
if (head == NULL)
{
insertAthead(head, val);
return;
}
node *n = new node(val);
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
// function to display each element in a linked list.
void display(node *head)
{
while (head->next != NULL)
{
cout << head->data;
head = head->next;
}
cout << head->data;
}
};
//main function
int main()
{
node *head; // line at which I think there is a problem
head->insert(head, 1);
head->insert(head, 2);
head->insert(head, 3);
head->insert(head, 4);
head->display(head);
return 0;
}
我認為問題出在第 1 行
node *head;
當我用node *head=new node(any integer value)
更改這一行時,代碼運行良好。
首先,您要將insert
、 insertAtHead
和display
移出Node
類。 這些是列表函數,不需要對Node
進行特殊訪問。
此外,您應該將head
初始化為 NULL(表示空列表)。
這意味着像這樣改變main
node *head = NULL;
insert(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
display(head);
然后你想改變
void insert(node *head, int val)
至
void insert(node *&head, int val)
就像您(正確地)使用insertAtHead
所做的一樣。
如果你想更進一步,你可以創建一個 List 類,沿着這些線
class List
{
public:
List() { root = NULL; }
void insert(int val);
void insertAtHead(int val);
void display();
private:
Node* root;
};
然后 main 看起來像這樣
int main()
{
List l;
l.insert(1);
l.insert(2);
l.insert(3);
l.insert(4);
l.display();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.