Reputation: 37
Here's my code so far:
struct stockRecord {
int code;
char name[MAXNAMELEN];
struct stockRecord* next;
};
struct stockRecord* temp = NULL;
struct stockRecord* head = NULL;
struct stockRecord* prevptr = NULL;
struct stockRecord* resfun(struct stockRecord* list)
{
temp = list;
if (head == NULL) head = list;
if (temp == NULL) {
return head;
} else {
if (prevptr == NULL) { //first node
if (strstr(temp->name, "ABC-") != NULL) {
temp = temp->next; //remove the current node
}
}
prevptr = list;
if (temp->next == NULL) {
return head;
} else {
return resfun(temp);
}
}
}
I don't know how to remove a node, and re-link the neighbour nodes. Then I'll need to return the head node to the main function.
Please can anyone help?
Thanks.
Upvotes: 2
Views: 1359
Reputation: 13574
Vega,
To remove the first element from a single-linked-list, all you really need to do is "forget" the first element (the head).
The general procedure for removing the first node is:
The general procedure for removing a node in the middle of a list is:
The general procedure for removing the last node is (I bet you can guess):
Recursion has nothing to do with it.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE_OF_NAME 12
#define SUCCESS 0
typedef struct Stock* stock;
struct Stock {
int code;
char name[SIZE_OF_NAME];
stock next;
};
stock head = NULL;
stock prev = NULL;
stock StripABC(stock curr)
{
if (strstr(curr->name, "ABC-") != NULL) {
// the first name contains "ABC-", so strip it.
head = head->next;
curr = head;
}
return head;
}
int main(int argc, char *argv[])
{
struct Stock a, b;
a.code = 1; strcpy(a.name, "ABC-");
b.code = 2; strcpy(b.name, "Widget");
head = &a;
head->next = &b;
StripABC(head);
printf("head->name: %s\n", head->name);
return SUCCESS;
}
Good luck with it. BTW, linked lists are STILL "stock in trade" for ansi-c programmers. I still work with them far too often ;-)
Cheers. Keith.
Upvotes: 3
Reputation: 228
Your code is a little hard to follow. But I'll try to help
This line:
temp = temp->next; //remove the current node
doesn't actually remove the node from the list. It should look something like this
prev->next = temp->next; // link the previous node past the current node
free(temp); // now that nothing is pointing to temp, you can deallocate the memory
return head; // we found our node, return the head of the list
In addition, you should add some code to check for the case where the node to be deleted is located at the head of the list. In this case, no relinking of nodes is required. Just set the head pointer to the next node in the list and then delete temp.
Upvotes: 1