title: C - Swapping nodes in a linked list with a sorting algorithm
body: <p>Im working on a project for school in which I need to sort a linked list with any sorting algorithm (preferably bubble) - please note that swapping each node data is not allowd as I am expected to swap the nodes. I can not paste all the code of my project as it is very wide and it is in Spanish, reason for which I will show you the parts in which I try to implement the node swapping.</p>
  
  <p>To sum up, the project itself is quite simple, a linked list where each node contains information of a person (name, last name, age, etc).</p>
  
  <p>I have to sort the list alphabetically. Please, bear in mind that I cannot implement the sorting nor the swapping algorithms in functions (That is to say, I cannot make a 'swapNodes' function and them implement it in the code.</p>
  
  <p>I managed to swap two nodes following this logic:</p>
  
  <pre><code>firstNode = auxiliar-&gt;next;
  auxiliar-&gt; next = firstNode-&gt;next;
  firstNode-&gt;next = auxiliar;
  </code></pre>
  
  <p>This works to swap 2 nodes perfectly.</p>
  
  <p>Problem is when I have to implement this logic with a sorting algorithm in order for it to sort all the list, and this is where I need you guys to help me.</p>
  
  <p>I have checked every post about bubblesorting and node swapping but I just can get it working.</p>
  
  <p>My  professor tried to help me, implementing my node swapping code in the following way (please note that as an example, the following code should sorts by age):</p>
  
  <pre><code>while (flag == 1) {
          auxiliar = firstNode;
          flag = 0;
  
          if (auxiliar-&gt;edad &gt; auxiliarSiguiente-&gt;edad) {
  
                firstNode = auxiliar-&gt;next;
                auxiliar-&gt; next = firstNode-&gt;next;
                firstNode-&gt;next = auxiliar;
                flag = 1;
  
          }
  
          auxiliar3 = firstNode;
  
          while (auxiliar-&gt;next != NULL ) {
  
              if (auxiliar-&gt;age &gt; auxiliarNext-&gt;age) {
  
                  auxiliar2 = auxiliar-&gt;next;
                  auxiliar-&gt;next = auxiliar2-&gt;next;
                  auxiliar2-&gt;next = auxiliar;
                  auxiliar3-&gt;next = auxiliar2;
  
              } else {
                  auxiliar = auxiliar-&gt;next;
              }
  
              auxiliar3 = auxiliar3-&gt;next;
  
          }
  
      }
  </code></pre>
  
  <p>And then again, this code works just fine when there are 2 nodes. In case there are more, it does not sort in a correct way. Moreover, Im not quite sure which sorting algorithm my professor used.</p>
  
  <p>Perhaps what my teacher did is wrong, or maybe there is a simpler way to do it.</p>
  
  <p>I greatly appreciate your feedback, as I could not manage to find a way to solve it myself.</p>
  
  <p>Hope you guys can help me!</p>