二重にリンクされたリストを作成してその値を出力しようとしていますが、出力に最初の値のみが表示され、プログラム全体がクラッシュします。
コードのどこに問題があるのか理解できません。
入力
3
1 2 3
期待される出力
1 2 3
現在の出力
1
#include<iostream>
#include<stdlib.h>
using namespace std;
class node //declation of node
{
public:
int data;
node *next;
node *prev;
};
node *makenode(node *head,int val) //function to create node
{
node *newnode=new node;
node *temp;
newnode->data=val;
newnode->next=0;
newnode->prev=0;
if(head==0) temp=head=newnode;
else
{
temp->next=newnode;
newnode->prev=temp;
temp=newnode;
}
return head;
}
void display(node *head) //display function
{
system("cls"); //clearing output screen
while(head!=0)
{
cout<<head->data<<" ";
head=head->next;
}
}
int main()
{
node *head;
head=0;
int val;
int s; //size of list
cout<<"ENTER THE SIZE OF LIST";
cin>>s;
system("cls");
for(int i=0;i<s;i++)
{
cout<<"ENTER THE "<<i+1<<" VALUE\n";
cin>>val;
head=makenode(head,val); //calling makenode and putting value
}
display(head); //printing value
return 0;
}
実際には何もリンクしていません。この行:if(head==0) temp=head=newnode;
リンクリストに値が含まれている唯一の理由です。最初の値はheadをそれに等しく設定し、headを印刷するとその値を取得します。リンクリストを適切に実行するには、ヘッドポインタとテールポインタが必要です。ヘッドはリストの最初の要素を指し、テールは最後の要素を指します。リストの最後に要素を追加するときは、tailを使用して最後の要素を見つけ、それにリンクします。リンクリストを頭と尾をカプセル化できるクラスにするのが最も簡単です。
struct Node {
public:
int data;
node *next;
node *prev;
Node(int data) : data(data), next(nullptr), prev(nullptr) {} // constructor
};
class LinkedList {
private:
Node* head;
Node* tail;
public:
LinkedList() { head = tail = nullptr; }
// This function adds a node to the end of the linked list
void add(int data) {
Node* newNode = new Node(data);
if (head == nullptr) { // the list is empty
head = newNode;
tail = newNode;
}
else { // the list is not empty
tail->next = newNode; // point the last element to the new node
newNode->prev = tail; // point the new element to the prev
tail = tail->next; // point the tail to the new node
}
}
};
int main() {
LinkedList lList;
lList.add(1);
lList.add(2);
// etc...
return 0;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加