I have expanded the code snippets into a complete .c file to provide a better understanding within the context:
struct node {
int data;
struct node* next;
}
typedef struct node nodde_t;
node_t* head;
/*bad code*/
void remove_list_entry_bad(node_t* entry){
node_t* prev = NULL;
node_t* walk = head;
while(walk != entry){
prev = walk;
walk = walk->next;
}
if(!prev)
head = entry->next;
else
prev->next = entry->next;
}
/*good code*/
void remove_list_entry_good(node_t* entry){
node_t** indirect = &head;
while ((*indirect) != entry)
indirect = &(*indirect)->next;
*indirect = entry->next;
}
int main(){
node_t n1, n2, n3;
n1.data = 45;
n2.data = 8;
n3.data = 32;
head = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = NULL;
remove_list_entry_good(&n2); /* instead : n1.next = &n3; */
return 0;
}
To keep things simple, I chose Integers as the data type for this implementation. The typedef is used to simplify writing node_t instead of struct node in the code. In C, you typically need to include the struct keyword whenever using a custom data type like node.
If pointers are unfamiliar, think of the Java version of this code with references replacing pointers:
package linked;
class Node {
int data;
Node next;
}
public class Test {
Node head;
/* bad code */
void remove_list_entry_bad(Node entry) {
Node prev = null;
Node walk = head;
while (walk != entry) {
prev = walk;
walk = walk.next;
}
if (prev == null)
head = entry.next;
else
prev.next = entry.next;
}
/* good code */
void remove_list_entry_good(Node entry) {
Node indirect = head;
while (indirect.next != entry)
indirect = indirect.next;
indirect.next = entry.next;
}
public static void main(String[] args) {
Node n1, n2, n3;
n1 = new Node();
n2 = new Node();
n3 = new Node();
n1.data = 45;
n2.data = 8;
n3.data = 32;
Test list = new Test();
list.head = new Node();
list.head.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = null;
list.remove_list_entry_good(n1);
Node walk = list.head.next;
while (walk != null) {
System.out.println("" + walk.data);
walk = walk.next;
}
}
}
The Node class utilizes a recursive definition, similar to methods that call themselves repeatedly. Placing the Node class inside the MyList class signifies it as a private class.
Edit
I discovered something intriguing in C where the type of indirect must be node_t** with double stars. Though the exact implications are unclear, it functions correctly.
Edit
I stumbled upon a simple and effective solution online!
void remove_list_entry_good(Node entry) {
Node temp = entry.next;
entry.value = temp.value;
entry.next = temp.next;
temp = null;
}