PhamHongViEHG
Junior
không biết có nhâm gì không mà chạy được nhưng không đúng phần tìm vị trí... nhập sao nó cũng ra vị trí thứ 1
Code:
#include<conio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<stdio.h>
using namespace std;
typedef struct node
{
int data;
struct node*next;
}node;
typedef struct list
{
node *phead;
node *ptail;
}list;
void init(list &l);
node *createnode(int x);
void addhead(list &l,node *new_ele);
void addtail(list &l,node *new_ele);
void input(list &l);
void output(list l);
void themgiua(list &l,node *new_ele,int h);
int timvitri(list &l,int m);
int n;
int main ()
{
int x,kt,m,k;
list l;
input(l);
output(l);
cout<<"\nnhap gia tri can chen vao dau: ";
cin>>x;
addhead(l,createnode(x));
output(l);
cout<<"\nnhap gia tri can chen vao cuoi: ";
cin>>x;
addtail(l,createnode(x));
output(l);
cout<<"\n nhap m: ";
cin>>m;
kt=timvitri(l,m);
if (kt==0)
cout<<"m khong xuat hien trong danh sach";
else
cout<<"m xuat hien trong danh sach o vi tri thu: "<<kt;
cout<<"\n nhap k va m: ";
cin>>k>>m;
kt=timvitri(l,m);
if (kt==0)
cout<<"m khong xuat hien trong danh sach!";
else
themgiua(l,createnode(k),m);
cout<<"sau khi chen k vao truoc m la: ";
output(l);
return 0;
}
void init(list &l)
{
l.phead = l.ptail= NULL;
}
node* createnode(int x)
{
node *p;
p = new node;
if (p == NULL)
cout<<" cap phat bo nho khong du";
p->data = x;
p->next = NULL;
return p;
}
void addtail(list &l,node *new_ele)
{
if (l.phead== NULL)
l.phead=l.ptail=new_ele;
else
{
l.ptail->next=new_ele;
l.ptail=new_ele;
}
}
void addhead(list &l,node *new_ele)
{
if (l.phead == NULL)
l.phead = l.ptail= new_ele;
else
{
new_ele->next =l.phead;
l.phead =new_ele;
}
}
void themgiua(list &l,node *new_ele,int h)
{
node *p =l.phead;
for (int i=1;i<h-1;i++)
p=p->next;
if (p==NULL)
cout<<"danh sach ngan hon vi tri da chon";
else
{
new_ele->next = p->next;
p->next = new_ele;
}
}
int timvitri(list &l,int m)
{
int vt=0;
while (l.phead !=NULL)
vt++;
return vt;
}
void input(list &l)
{
int x,n;
cout<<"nhap so luong node: ";
cin>>n;
init(l);
for (int i=0;i<n;i++)
{
cout<<"nhap phan tu thu "<<i+1<<": ";
cin>>x;
node*p= createnode(x);
addhead(l,p);
}
}
void output(list l)
{
/* for (node* p = l.phead; p; p = p->next)
cout << p->data << " --> ";
cout << "NULL";*/
while (l.phead !=NULL)
{
cout<<l.phead->data<<" -> ";
l.phead=l.phead->next;
}
cout<<"NULL";
}