【发布时间】:2014-10-12 17:57:09
【问题描述】:
我一直在学习 C++ 中单链表的实现。 问题是我理解了单链表背后的概念,但我无法猜测我在代码中哪里出错了。 每当我插入一个新节点时,它都会占据第一个位置(即头部),并且列表的大小始终为 1。 我试图解决它,但有时显示功能会变成无限循环。 我对此一无所知。 一个星期以来一直困扰着我。
我只能猜测,我没有在代码中正确引用地址。 我搞砸了指针吗?帮助我理解我所犯的错误。谢谢。
SLLCLAS.CPP
#include<iostream>
#include<conio.h>
class node{
public:
int data;
node *next;
};
class sll{
private:
node *head;
public:
ssl(){
head=NULL;
}
void display();
void insert(int,int);
};
void sll::display(){
if(head==NULL){
cout<<"List is Empty";
}else{
cout<<"\n";
for(node *t=head;t!=NULL;t=t->next){
cout<<t->data<<"->";
}
cout<<"\n";
}
void sll::insert(int position,int data){
node *temp=new node();
temp->data=data;
if(position<0){
cout<<"\nPosition not valid";
}else if(head==NULL || position==1){
temp->next=head;
head=temp;
}else{
node *p,*q;
q=head;
int count=1;
while(count<position && q!=NULL){
count++;
cout<<"\nCount:"<<count;
p=q;
q=q->next;
}
p->next=temp;
temp->next=q;
delete(temp);
}
int main(){
clrscr();
sll list;
int ch,val,pos;
do{
cout<<"\nSINGLY LINKED LIST\n1: Insert\n2: Delete\n3: Display\n Enter your choice:";
cin>>ch;
switch(ch){
case 1:
cout<<"\nEnter the position:";
cin>>pos;
cout<<"\nEnter the value:";
cin>>val;
list.insert(pos,val);
list.display();
break;
case 2:
break;
case 3:
list.display();
break;
default:
cout<<"\nWrong choice";
}
cout<<"\nDo you want to continue(1/0):";
cin>>ch;
}while(ch!=0);
getch();
}
EDIT:
我正在 Windows 8.1 64 位上的 Turbo C++ 3.0 版上运行代码 使用dosbox。
【问题讨论】:
-
缩进你的代码。停止在数据结构函数中使用 IO。
-
请提供一个没有调试代码的可读示例
-
<iostream.h>?标头应为<iostream>。另外,您是从哪里得知分号遵循#include 指令的?至于你的问题,你是先在纸上画出链表吗?您应该在编写一行代码之前这样做。一旦您了解了链接如何在纸上 工作,您就可以将您在纸上的内容转移到 C++ 程序中。如果 C++ 不能正常工作,你需要知道你的程序在哪里偏离了计划。 -
@PaulMcKenzie,那个(分号)是我,我认为(我使用的在线格式化程序搞砸了,所以我恢复了)
-
1.将位置作为数字给出对列表不友好,
ssl::insert应该将位置作为指针或迭代器。 2.使用构造函数(ssl::ssl())代替void ssl::initList()
标签: c++ linked-list singly-linked-list