C++ program to swap links of a Linked List
This works as long as 2 conditions are met.


val1 and val2 are in the list.
Neither are in the head node.


Otherwise you access stuff via null pointers:

  void swapLinks(T val1, T val2)
  {
    Node* prevNode1 = nullptr;
    Node* prevNode2 = nullptr;
    Node* nextNode1 = nullptr;
    Node* nextNode2 = nullptr;
    Node* node      = head;
    Node* node1     = search(val1);
    Node* node2     = search(val2);

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node-&gt;next != node1)
    {
      node = node-&gt;next;
    }
    if(node-&gt;next == node1)
    {
      prevNode1 = node;
      nextNode1 = node1-&gt;next;
    }

    node = head;

    // This will not find values in the "head node"
    // If the value is in head the you will not find a previous node.
    // You need to take into account this special case at the bottom.
    while(node-&gt; next != node2)
    {
      node = node-&gt;next;
    }
    if(node-&gt;next == node2)
    {
      prevNode2 = node;
      nextNode2 = node2-&gt;next;
    }

    // HERE YOU HAVE some issues.
    // prevNode1 or prevNode2 or node1 or node2 may be nullptr
    // If any of these values are null the code below will be UB.
    prevNode1-&gt;next = node2;
    Node* tmp       = node2-&gt;next;
    node2-&gt;next     = node1-&gt;next;
    prevNode2-&gt;next = node1;
    node1-&gt;next     = tmp;
  }