Thursday, 9 August 2012
List (C++ code)
class Node{
public:
int data;
Node* next;
Node(){
next=NULL;
}
Node(Node *next,int data);
void set(int data);
void get();
};
class List{
public:
Node* start;
List();
List(int data);
void Add(int pos,int data);
void Add(int data);
int getSize();
int getPosForData(int pos, int data);
int getPos(int pos);
void removePos(int pos);
void remove(int data);
~List();
};
#include<iostream>
#include"List.h"
using namespace std;
Node :: Node(Node *next,int data){
this->next = next;
this->data = data;
}
void Node :: get(){
Node *tmp = this->next;
while (tmp != NULL){
cout<<this->data<<endl;
tmp = tmp->next;
}
}
void Node :: set(int data){
Node *tmp;
tmp = new Node;
tmp->data = data;
this->next=tmp;
}
List :: List(){
start = NULL;
}
List :: List(int data){
start = new Node (NULL,data);
}
List ::~List (){
while (start!=NULL){
Node *todel=start;
start = todel->next;
delete todel;
}
}
void List :: removePos(int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &(*prev)->next;
}
Node * todel = (**prev).next;
(*prev) = todel->next;
delete todel;
}
void List :: Add (int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
prev = &(*prev)->next;
}
*prev = new Node (NULL,data);
}
void List :: Add(int data,int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &((*prev)->next);
}
*prev = new Node ((*prev)->next,data);
}
int List :: getSize (){
int rez = 0;
Node *next = start;
while(next!=NULL){
rez++;
next = next->next;
}
return rez;
}
int List :: getPosForData(int pos,int data){
int rez=-1;
Node *next = start;
while((next!=NULL)&&(next->data!=data)){
rez++;
next = next->next;
if(data == next->data){
return rez;
}
}
return -1;
}
int List :: getPos(int pos){
Node *rez = start;
for (int i=0;i<pos;i++){
rez = rez->next;
}
return rez->data;
}
void List ::remove(int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
while((*prev)->data != data){
prev = &(*prev)->next;
if((*prev) == NULL) return;
}
Node * todel = (*prev)->next;
(*prev) = todel->next;
delete todel;
}
}
int mai (){
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment