问题
void sortlist()
{
struct node *a;
struct node *temp=head;
struct node *temp1=head->next;
while(temp!=NULL)
{
while(temp1->next!=NULL)
{
if(temp->data > temp1->data)
{
a->data=temp->data;
temp->data=temp1->data;
temp1->data=a->data;
}
else
{
temp1=temp1->next;
}
}
temp=temp->next;
}
}
//I am new to data structures.i am encountering some problem here while trying to sort elements of linked list.list does not get sorted.any help is greatly appreciated.
回答1:
a is an uninitialised pointer so the line
a->data=temp->data;
invokes undefined behaviour. Crashing is the most likely result here as you'll try to write to memory at an undefined address that may not be writeable by your code or may be in use by another part of your program.
You could fix this by giving a the same type as temp->data instead.
void sortlist()
{
int a; // change type to match node->data if required
...
if(temp->data > temp1->data)
{
a=temp->data;
temp->data=temp1->data;
temp1->data=a
}
...
}
EDIT: There is also a potential NULL dereference crash in the line while(temp1->next!=NULL). The code below shows a potential implementation of sortlist which avoids this.
void sortlist()
{
struct node *ptr=head;
while(ptr!=NULL) {
struct node *next;
if (ptr == NULL)
return;
next = ptr->next;
while(next!=NULL) {
if(ptr->data > next->data) {
int a=ptr->data;
ptr->data=next->data;
next->data=a;
}
next = next->next;
}
ptr=ptr->next;
}
}
回答2:
I made changes in the code and add the comments for the changes
void sortlist()
{
// struct node *a; /* this is not required. */
/* NULL checks are required,if head is NULL,head->next will crash.*/
if(head == NULL || head->next == NULL) return;
struct node *temp=head;
struct node *temp1=head->next;
while(temp!=NULL)
{
while(temp1->next!=NULL)
{
if(temp->data > temp1->data)
{
/* assuming you data is integer*/
int d=temp->data;
temp->data=temp1->data;
temp1->data=d;
}
//else /* else is not required, better to remove it.*/
//{
temp1=temp1->next;
//}
}
temp=temp->next;
}
}
回答3:
//at last i found answer to my own problem and this is the solution,thanks for your help buddies
void sortlist()
{
struct node *temp=head;
int s;
struct node *temp1=temp->next;
while(temp!=NULL)
{
temp1=temp->next;
while(temp1!=NULL)
{
if(temp->data > temp1->data)
{
s=temp->data;
temp->data=temp1->data;
temp1->data=s;
}
temp1=temp1->next;
}
temp=temp->next;
}
}
来源:https://stackoverflow.com/questions/17815939/sorting-element-from-linked-list