title: Sorting a linked list in C
body: <p>I'm trying to sort a linked list by finding the largest value, deleting it from its position, and then inserting it at the top of the list.</p>
  
  <p>The difficulty I'm running into is the actual deleting and inserting at the top. The issue seems to be in the if condition in the while loop contained within the sortList function, but I'm not sure how to fix it.</p>
  
  <p>Any help would be appreciated.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct node{
      int num;
      struct node *next;
  } Node, *NodePtr;
  
  void printList(NodePtr np);
  NodePtr makeList(void);
  NodePtr makeNode(int n);
  NodePtr sortList(NodePtr list);
  
  int main(void) {
      NodePtr list;
      printf("Enter numbers for the list (0 to end)\n");
      list = makeList();
      printList(list);
      list = sortList(list);
      printList(list);
      return 0;
  }
  
  NodePtr makeList(void) {
      NodePtr makeNode(int), np, top, last;
      int n;
      top = NULL;
      if(scanf("%d", &amp;n) != 1)n = 0;
      while(n != 0) {
          np = makeNode(n);
          if(top == NULL)top = np;
          else last-&gt;next = np;
          last = np;
          if(scanf("%d", &amp;n)!=1)n=0;
      }
      return top;
  }
  
  
  void printList(NodePtr np) {
      while(np != NULL) {
          printf("%d\n", np-&gt;num);
          np = np-&gt;next;
      }
  }
  
  NodePtr makeNode(int n) {
      NodePtr np = (NodePtr)malloc(sizeof(Node));
      np-&gt;num = n;
      np-&gt;next = NULL;
      return np;
  }
  
  NodePtr sortList(NodePtr list) {
      NodePtr top = list;
      NodePtr curr = NULL;
      NodePtr largest;
      NodePtr prev;
      prev = NULL;
      curr = top;
      largest = top;
  
      while(curr != NULL) {
          prev = curr;
          if(curr-&gt;num &gt; largest-&gt;num) {
              largest = curr;
              prev-&gt;next = curr-&gt;next;
              largest-&gt;next = top;
          }
          curr = curr-&gt;next;
      }
      if(prev == NULL) {
          largest-&gt;next = top;
          return largest;
      }
      return largest;
  }
  </code></pre>