我刚刚第一次创建了一个双链表,尽管它提供了打印功能,但它没有给出任何输出。肯定有一些小错误我无法解决,还有一个小问题我想问,我应该如何调试这些代码来自己找出错误。请评论在VScode中调试代码的任何教程的任何讲座提前感谢
这是代码:
#include<iostream>
using namespace std;
struct node{
int data;
struct node* next;
struct node* prev;
};
struct node* head;
struct node* getnewnode(int x){
struct node* tempnode = new node();
tempnode->data=x;
tempnode->next=NULL;
tempnode->prev=NULL;
return tempnode;
};
void insertathead(int x){
struct node* newnode = getnewnode(x);
if (head == NULL)
{
head == newnode;
return;
}
head->prev=newnode;
newnode->next=head;
head=newnode;
}
void print(){
struct node* tempprint = head;
while (tempprint != NULL)
{
cout<<tempprint->data<<"_";
tempprint=tempprint->next;
}
cout<<endl;
}
void reverseprint(){
struct node* tempreverse = head;
if (tempreverse == NULL)
{
return;//empty list
}
while (tempreverse->next != NULL)
{
tempreverse = tempreverse->next;
}
//now traversing backwards using prev
while (tempreverse != NULL)
{
cout<<tempreverse->data<<"_";
tempreverse=tempreverse->prev;
}
}
void insertattail(int x){
struct node* newnode = getnewnode(x);
struct node* temptail = head;
while (temptail->next != NULL)
{
temptail = temptail->next;
}
temptail->next= newnode;
newnode->prev=temptail;
newnode->next=NULL;
}
int main(){
head=NULL;//empty list
insertathead(2);
insertathead(4);
insertathead(8);
insertattail(3);
//list - 2_4_8_3
print();
reverseprint();
print();
return 0;
}
在这么短的时间内找到了答案。有一个错误导致了21号线上的所有问题我在比较head和newnode,相反,我应该将newnode的值代入head。谢谢