It might be for pedantic purposes but not homework. I have below question about ‘Sorting a singly linked list’ (Any kind of list for that matter) Assume for this questions we want to sort in ascending order of values in each node.
Does this question expect me to just sort the list by swapping the values of each node in the list so that the values are in some order(ascending/descending). Here the original values of nodes (before sorting) would be changed in order to reflect the sorted list. Here the same earlier head pointer is returned but now having the smallest element in it, which might be different than its earlier element.
Like this C code I have below(The code below might not compile as is , but I have it working fine. Posted here as illustrative to clear my point):
struct lnk_lst
{
int val;
struct lnk_lst *next;
};
main()
{
//Assume curr is the head node of the singly linked list created with some values
curr = llist_bubble_sort(curr);
}
struct lnk_lst* llist_bubble_sort(struct lnk_lst *lst)
{
int i,n=0,tmpint;
struct lnk_lst *tmp=lst,*tmp2=lst;
while(tmp->next)
{
lst = tmp2;
while(lst->next)
{
if(lst->val > lst->next->val)
{
tmpint = lst->val;
lst->val = lst->next->val;
lst->next->val = tmpint;
}
lst = lst->next;
}
tmp = tmp->next;
}
return tmp2;
}
OR
Is it expected to that the pointer to the node with the smallest element(assuming ascending order) in the original ordering is moved as new head node, then the node having the next smallest element is linked to the head node, and so on such that the list is reordered completely and now the head node returned is not same pointer as earlier.
If the interpretation of list sort is this second, then I have to see how yet get the idea done in code.
The whole idea behind linked lists is that the links can be changed without affecting the content. Changing a pointer sometimes involves creating a pointer to pointer variable. Also: if you only swap the contents, you could just as well leave out the ->next pointers, use an array instead, and swap the array’s contents.
IMHO the natural way of sorting a linked list is mergesort. The fragment below splits the list in two part: the nodes that are already in place, and those that are not. The second list is sorted, and the two lists are merged. Both splitting&merging involve some pointer-to-pointer variables.
RESULT: