yes i mean sorting by switching links
[insert]
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
void getdata();
void display(struct node *);
void selection_sort();
struct node *start;
int main(void){
start = NULL;
getdata();
display(start);
selection_sort();
display(start);
return 0;
}
void selection_sort()
{
struct node *p, *q, *r, *s;
p = start;
r = start;
q = p ->link;
s = q;
// nodes being compared are adjacent and p is first node
while(p ->link != NULL)
{
s = q = p->link;
while(q != NULL)
{
if( p == start && p ->link == q)
{
if(p ->data > q ->data)
{
struct node *temp;
temp = p ->link;
p->link = q->link;
q ->link = temp;
q = p->link;
s = p;
p = r = q;
}
}
else if( p == start && p ->link != q)
{
if(p ->data > q ->data)
{
struct node *temp;
temp = p->link;
p ->link = q ->link;
q ->link = s;
s ->link = p;
q = r->link;
s = p;
p = r = q;
start = p;
}
}
else if(p != start && p->link == q)
{
if(p ->data > q ->data)
{
struct node *temp1, *temp2;
temp1 = q->link;
temp2 = p->link;
p->link = q->link;
q ->link = temp2;
r->link = q;
q = temp1;
p = r->link;
s = p ->link;
}
}
else if(p != start && p->link != q)
{
if(p ->data > q->data)
{
struct node *temp1, *temp2;
temp1 = p->link;
temp2 = q->link;
p ->link = q->link;
q ->link = s;
s ->link = p;
r ->link = q;
p = q;
s = q;
q = temp2;
}
}
s = q;
q = q->link;
}
r = p;
p = p->link;
}
}
void getdata(){
struct node *p, *q;
char ch;
int val;
do{
printf("\nEnter data for the list");
scanf("%d", &val);;
// adding the node for the first time
if( start == NULL)
{
p = malloc(sizeof(struct node));
p ->data = val;
p ->link = NULL;
start = p;
}
else
{
p = start;
while(p ->link != NULL)
p = p ->link;
q = malloc(sizeof(struct node));
q ->data = val;
q ->link = NULL;
p ->link = q;
}
printf("\nAny more data");
ch = getche();
}while (ch == 'y' || ch == 'Y');
}
void display(struct node *p){
struct node *temp;
temp = p;
while(temp != NULL){
printf("\n%d", temp->data);
temp = temp->link;
}
}
I am getting errors but now i am totally lost in this :-(