I am using C#, and I wanted to sort a linked list without using extra memory.
Input: listptr→ 11 → 8 → 2→ 4 → 5
Output: listptr→ 2 → 4 → 5 → 8 → 11
This is my class:
public class SNode
{
public int data;
public SNode next;
}
Should I create a new temp variable to store the temp list?
Like SNode temp = new SNode(2,NULL);?
This is a homework assignment.
I should think the point of the exercise is to sort the list in place without creating a copy of the whole thing (so you can presumably use a small amount of memory in the form of variables to help with the sort).
The easiest way to code it is probably to use a bubble sort (although this is horribly inefficient for large lists). The trick is to use a variable to keep track of the node before the current pair, since you will have to adjust its
nextif you need to swap the order of the nodes in the pair.As others have pointed out, in a real project you would use the .NET framework to do the heavy lifting for you, but I guess this is a theoretical exercise in pointer manipulation so you’re supposed to code it all for yourself.