【发布时间】:2018-04-04 04:09:19
【问题描述】:
自从我开始学习链表已经一周了,我只学习了单链表。所以今天我实现了我在 C++ 中学到的链表,当我尝试运行它时,代码进入了一些随机数的无限循环。我尝试调试代码,但我找不到代码有什么问题。代码如下。感谢您的帮助。谢谢
#include <iostream>
using namespace std;
struct node{
int data;
node * next;
};
class singly{
private:
node * head,*tail;
public:
singly(){
head=NULL;
tail=NULL;
}
void createNode(int value){
node * temp = new node;
temp->data=value;
temp->next=NULL;
if(head==NULL){
head=temp;
tail=temp;
temp=NULL;
}
else{
tail->next=temp;
tail=temp;
}
}
void display(){
node * temp = new node;
head=temp;
while(temp!=NULL){
cout << temp->data << "\t" << endl;
temp->next=temp;
}
}
void insert_end(int value){
node*newnode = new node;
node*temp = new node;
newnode->data=value;
newnode->next=NULL;
temp=head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next=newnode;
}
void delete_node(){
node*current = new node;
node*previous = new node;
current = head;
while(current->next!=NULL){
previous=current;
current=current->next;
}
tail=previous;
previous->next=NULL;
delete current;
}
};
int main(){
singly lists;
lists.createNode(32);
lists.createNode(654);
lists.createNode(34);
lists.createNode(234);
cout<<"\n--------------------------------------------------\n";
cout<<"---------------Displaying All nodes---------------";
cout<<"\n--------------------------------------------------\n";
lists.display();
cout<<"\n--------------------------------------------------\n";
cout<<"-----------------Inserting At End-----------------";
cout<<"\n--------------------------------------------------\n";
lists.createNode(55);
lists.display();
cout<<"\n--------------------------------------------------\n";
cout<<"-----------------Deleing At End-------------------";
cout<<"\n--------------------------------------------------\n";
lists.delete_node();
lists.display();
}
【问题讨论】:
-
什么时候进入死循环?您不能指望我们为您调试整个代码。
-
我建议你对
new关键字的作用做一些研究,因为从这段代码来看你并不真正了解它 -
display和delete_node都坏了。您应该只在将节点添加到列表的函数中写入new。不要使用new创建指针——如果您想要一个与head具有相同值的指针,您只需要node* temp = head;。 -
顺便说一句,
insert_end对于带有尾指针的列表来说是不必要的复杂,此外,在末尾插入是createNode所做的。 -
@molbdnilo 非常感谢您的帮助
标签: c++ linked-list singly-linked-list