Can we add nodes in singly linked list?

Well, the simplest way of not doing something is not to do it.

Tracing what the values of things are through your implementation:

// Insert a node to the beginning of the linked list void addNodeBegin [node_t *head, int val] { // assume head = [val1, ...] node_t *newNode = NULL; newNode = malloc[sizeof[node_t]]; newNode->val = val; // newNode=[val, null] newNode->next = head->next; // newNode=[val, ...] head->next = newNode; // head = [val1, [val, ...]] node_t *tmp = NULL; tmp = malloc[sizeof[node_t]]; tmp->val = head->val; // tmp = [val1, undefined] head->val = newNode->val; // head = [val, [val, ...]] head->next->val = tmp->val; // head = [val, [val1, ...]] free[tmp]; }

Firstly, the only thing temp is doing is storing a copy of head->val, so you could store the value directly instead by setting newNode->val before overwriting head->val:

// Insert a node to the beginning of the linked list void addNodeBegin [node_t *head, int val] { // assume head = [val1, ...] node_t *newNode = malloc[sizeof[node_t]]; // no need to set to NULL first newNode->val = head->val; // newNode=[val1, undefined] newNode->next = head->next; // newNode=[val1, ...] head->next = newNode; // head = [val1, [val1, ...]] head->val = val; // head = [val, [val1, ...]] }

Secondly, this is doing something different to adding a node at the beginning of a list. It is inserting a node after the beginning, then swapping the values between the first and second nodes. This will matter as very commonly singly linked lists have multiple heads, either for performance reasons or to implement specific algorithms, so operations shouldn't change the tail of the list when they prepend to it. It also means you have to have two different operations - appending to an empty list [NULL] and appending to a non-empty list.

The example implementation of push[] takes a pointer to the pointer to the head of the list, creates a new node and mutates that pointer to point to the new node. This seems harder to use than necessary, as it requires taking the address of the pointer to the head.

node_t* head = NULL; push [ &head, 1 ]; push [ &head, 2 ]; push [ &head, 3 ]; push [ &head, 4 ]; node_t* head2 = head; push [ &head2, 5 ];

Personally I'd just return the pointer to the new node:

node_t* cons [int val, node_t* next] { node_t * new_node = malloc[sizeof[node_t]]; new_node->val = val; new_node->next = next; return new_node; } node_t* head = cons[4, cons[3, cons[2, cons[1, NULL]]]]; node_t* head2 = cons[5, head];

'Cons' is short for construct, a traditional name for the construction of singly linked lists in this manner.

Video liên quan

Chủ Đề