You are on page 1of 4

struct Node{

int key;
Node *next;
};

struct List{
Node* head;
Node* tail;
};

Node* createNode(int key){


Node* node = new Node;
node->key=key;
node->next=NULL;
return node;
}

List* createList(){
List* list = new List;
list->head=NULL;
list->tail=NULL;
}

void addHead(List* &list, int key){


Node *newHead = createNode(key);
if (list->head==NULL){
list->head = newHead;
list->tail = list->head;
}
else {
newHead->next = list->head;
list->head = newHead;
}
}

void addTail(List* &list, int key){


Node *newTail = createNode(key);
if (list->head==NULL)
addHead(list,key);
else{
list->tail->next=newTail;
list->tail=newTail;
}
}

void addAfterQ(List* &list, Node* &p, Node* &q){


if (q==NULL){
p->next = q->next;
q->next=p;
if (q==list->tail)
list->tail=p;
}
else
addHead(list,p->key);
}

bool deleteHead(List* &list){


if (list->head==NULL)
return false;
Node *oldHead = list->head;
list->head = list->head->next;
delete oldHead;
if (list->head==NULL)
list->tail=NULL;
return true;
}

bool deleteAfterQ(List* &list, Node* q){


Node* p = q->next;
if (q==NULL || list->head==NULL || p==NULL)
return false;
p=q->next;
if (p==list->tail)
list->tail = q;
q->next = p->next;
delete p;
return true;
}

bool deleteX(List* &list, int x){


Node *p = list->head;
Node *q = NULL;
while (p!=NULL && p->key!=x){
q=p;
p=p->next;
}
if (p==NULL)
return false;
if (q!=NULL)
deleteAfterQ(list,q);
else
deleteHead(list);
return true;
}

void deleteList(List* &list){


Node *p;
while (list->head!=NULL){
p=list->head;
list->head=list->head->next;
delete p;
}
}

Node* findX(List* list, int x){


Node *p = list->head;
while (p!=NULL && p->key!=x)
p=p->next;
if (p!=NULL && p->key==x)
return p;
return NULL;
}

void printList(List* list){


Node *p = list->head;
cout<<endl;
while (p!=NULL){
cout<<p->key<<" ";
p=p->next;
}
cout<<endl;
}

void sortList(List* &list){


Node *p = list->head;
Node *q;
Node *min;
//selection sort with info sorting
while (p!=list->tail){
min=p;
q=p->next;
//find node with min value
while (q!=list->tail){
if (q->key<min->key)
min=q;
q=q->next;
}
//swap info
int temp = p->key;
p->key = min->key;
min->key = temp;
//
p=p->next;
}
}

void quickSortList(List* &list){


Node *p;
Node *x;

List* left = createList();


List* right = createList();

x=list->head;
list->head = x->next;

while (list->head!=NULL){
p=list->head;
list->head=p->next;
if (p->key<=x->key)
addHead(left,p->key);
else
addHead(right,p->key);
}

quickSortList(left);
quickSortList(right);

if (left->head!=NULL){
list->head = left->head;
list->tail->next = x;
}
else
list->head = x;

x->next = right->head;
if (right->head!=NULL)
list->tail = right->tail;
else
list->tail = x;
}

You might also like