#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std ;
struct Node
{
int data;
Node *pNext;
};
struct Singlelist
{
Node *pHead ;
};
void Initialize (Singlelist &list)
{
list.pHead=NULL;
}
Node *Createnode (int d)
{
Node *pNode = new Node ;
if(pNode != NULL)
{
pNode->data =d;
pNode->pNext=NULL;
}
else
{
cout<<" error allocated memory ";
}
return pNode ;
}
void Printlist (Singlelist list)
{
Node *pTmp = list.pHead;
if(pTmp == NULL)
{
cout<<" The list is empty !";
return ;
}
while (pTmp != NULL)
{
cout<<pTmp->data<<"\t";
pTmp=pTmp->pNext;
}
}
int Sizeoflist (Singlelist list)
{
Node *pTmp=list.pHead;
int nSize =0;
while (pTmp != NULL)
{
pTmp != pTmp->pNext;
nSize ++;
}
return nSize ;
}
void Insertfirst(Singlelist &list , int d)
{
Node *pNode=Createnode(d);
if(list.pHead==NULL)
{
list.pHead=pNode;
}
else
{
pNode->pNext=list.pHead;
list.pHead=pNode;
}
}
void Insertlast(Singlelist &list , int d)
{
Node *pNode = Createnode(d);
if(list.pHead==NULL)
{
list.pHead=pNode;
}
else
{
Node *pTmp=list.pHead;
while(pTmp->pNext != NULL)
{
pTmp=pTmp->pNext;
}
pTmp->pNext=pNode;
}
}
void Insertmid(Singlelist &list,int pos, int d)
{
if(pos <0 || pos >= Sizeoflist(list))
{
cout<<" Not valid position do insert ";
return ;
}
if(list.pHead==NULL|| pos==0)
Insertfirst(list,d);
else if(pos == Sizeoflist(list)-1)
Insertlast(list,d);
else
{
Node *pNode=Createnode(d);
Node *pIns =list.pHead;
Node *pPre =NULL;
int i=0;
while (pIns != NULL)
{
if(i==pos)
break;
pPre=pIns;
pIns=pIns->pNext;
i++;
}
pNode->pNext=pIns;
pPre->pNext=pNode;
}
}
int main()
{
Singlelist list;
Initialize(list);
Insertfirst(list,10);
Insertlast(list,113);
Insertfirst(list,5);
Insertfirst(list,7);
Insertfirst(list,3);
Insertlast(list,18);
Insertmid(list,2,17);
Printlist(list);
int n=Sizeoflist(list);
cout<<"\nco "<<n<<" Node :";
return 0;
}
Chạy chương trình danh sách liên kết đơn nhưng không in ra thông tin gì
int Sizeoflist (Singlelist list)
{
Node *pTmp=list.pHead;
int nSize =0;
while (pTmp != NULL)
{
pTmp != pTmp->pNext; //<----------------
nSize ++;
}
return nSize ;
}
1 Like
em sửa được lỗi rồi , em cảm ơn nhiều ạ
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?