gpt4 book ai didi

c++ - 向链表的末尾添加值并从前面删除 C++

转载 作者:行者123 更新时间:2023-11-28 02:12:02 25 4
gpt4 key购买 nike

我正在尝试将项目添加到列表的末尾并从列表的开头删除它们。该程序编译但在我尝试添加项目时崩溃。我是这个概念的新手,需要一些时间才能完全适应。任何帮助表示赞赏..谢谢!

  #include<iostream>
using namespace std;



struct myNode
{
int val;
struct myNode *next;
};


class Cll
{

public:
myNode* head = new myNode;
myNode* tail = new myNode;

Cll()
{
head = NULL;
tail = NULL;
}
myNode* createAnode(int value)
{
myNode* temp;
temp = new myNode;

temp->val = value;
temp->next = NULL;
return temp;
}
void addingValues()
{
int numb;
cout<<"Enter the number to be added: ";
cin>>numb;
myNode *temp, *p;
temp = createAnode(numb);

p = head;
p = p-> next;
temp -> next = NULL ;
p -> next = temp;

}
void deletingValues()
{
myNode *s;
s = head;
head = s->next;
}

void showValues()
{
struct myNode *temp2;

temp2 = head;
while (temp2)
{
cout<<temp2->val<<"->";
temp2 = temp2->next;
}
cout<<"NULL"<<endl;
}

};



int main()
{

int pick ;
Cll cll;
int again;




do
{

cout<<"1.add"<<endl;
cout<<"2.delete"<<endl;
cout<<"3.show"<<endl;
cout<<"Enter choice : ";
cin>>pick;
switch(pick)
{
case 1:
cll.addingValues();
cout<<endl;
break;

case 2:
cll.deletingValues();
break;
case 3:
cll.showValues();
cout<<endl;
break;

}
cout << "Enter 1 to see again, enter 2 to quit"<< endl;
cin >> again;

} while (again == 1);




}

最佳答案

您正在使用 C++ 编程,所以我建议使用 std::list

但是如果你喜欢自己做,喜欢在你的单个喜欢列表前面添加一个节点,你首先要检查它是否是第一个节点。如果它是第一个节点,则您的新节点是 headtail。如果不是,则新节点是表头,其后继者是列表的旧表头。像这样调整您的代码:

void addingValues()
{
int numb;
cout << "Enter the number to be added: ";
cin >> numb;
myNode *newNode = createAnode(numb);

if ( head == NULL ) // if list is empty the new node is the head and the tail
{
head = tail = newNode;
return;
}

tail->next = newNode; // successor of last node is new node and new node is tail
tail = newNode;
}

要从列表前面删除一个节点,您必须检查列表是否不为空以及它是否是列表中的最后一个节点:

void deletingValues()
{
if ( head == NULL )
return;

myNode *temp = head->next;
delete head;
head = temp;
if ( head == NULL )
tail == NULL;
}

关于c++ - 向链表的末尾添加值并从前面删除 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35297106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com