Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <fstream>
- #include <stdlib.h>
- using namespace std;
- struct Li
- {
- int value;
- Li* nextitem;
- };
- typedef struct Li Listitem;
- struct iL
- {
- int nofitems;
- Listitem* firstitem;
- };
- typedef struct iL intList;
- Listitem* createnewlistitem(int x)
- {
- //Listitem* newitem = (Listitem*)new(sizeof(Listitem));
- Listitem* newitem = new Listitem[1];
- if (newitem == NULL)
- {
- cout<<"Error";
- exit(-1);
- }
- newitem->value=x;
- newitem->nextitem=NULL;
- return newitem;
- }
- intList* createnewlist()
- {
- //intList* newlist=new(sizeof(intList));
- intList* newlist = new intList[1];
- if (newlist == NULL)
- {
- cout<<"ERror #2";
- exit(-1);
- }
- newlist->nofitems=0;
- newlist->firstitem=NULL;
- return newlist;
- }
- void additemtofront(intList* i, Listitem* l)
- {
- if (i->nofitems==0)
- {
- i->firstitem=l;
- i->nofitems=1;
- }
- else
- {
- l->nextitem=i->firstitem;
- i->firstitem=l;
- i->nofitems++;
- }
- }
- void deletefromback(intList* i)
- {
- if(i->nofitems==0)
- {
- cout<<"Stop trying to delete"<<endl;
- return;
- }
- if(i->nofitems==1)
- {
- Listitem* onlyitem=i->firstitem;
- delete(onlyitem);
- onlyitem=NULL;
- i->firstitem=NULL;
- i->nofitems=0;
- }
- else
- {
- Listitem* currentitem=i->firstitem;
- Listitem* seconditem=currentitem->nextitem;
- while(seconditem->nextitem!=NULL)
- {
- currentitem=seconditem;
- seconditem=currentitem->nextitem;
- }
- delete(seconditem);
- seconditem=NULL;
- currentitem->nextitem=NULL;
- i->nofitems--;
- }
- }
- void additemtoback(intList* i, Listitem* l)
- {
- if (i->nofitems==0)
- {
- additemtofront(i,l);
- return;
- }
- Listitem* currentitem = i->firstitem;
- while(currentitem->nextitem!=NULL)
- currentitem=currentitem->nextitem;
- currentitem->nextitem=l;
- i->nofitems++;
- }
- void printList(intList* l)
- {
- if (l==NULL)
- {
- cout<<" NO LIST\n";
- return;
- }
- if (l->nofitems==0)
- {
- cout<<"No items to print!\n";
- return;
- }
- cout<<l->nofitems<<",";
- Listitem* currentItem = l->firstitem;
- while(currentItem->nextitem!=NULL)
- {
- cout<<currentItem->value<<"->";
- currentItem=currentItem->nextitem;
- }
- cout<<currentItem->value<<endl;
- }
- int main()
- {
- intList* mylist=createnewlist();
- printList(mylist);
- Listitem* myitem=createnewlistitem(13);
- additemtofront(mylist,myitem);
- printList(mylist);
- Listitem* myitemTwo=createnewlistitem(24);
- additemtofront(mylist,myitemTwo);
- printList(mylist);
- Listitem* myitemthree=createnewlistitem(10);
- additemtoback(mylist,myitemthree);
- printList(mylist);
- deletefromback(mylist);
- printList(mylist);
- int dummy=0;
- cin>>dummy;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment