Deleting Linked LIst in C - c

I just stuck with the problem couple of hours, trying to find where my code breaks. I know how to delete linked list but something doesn't work.
First it is a very simple struct with a dataype of int and 2 struct *next and *prev.
struct _list_{
struct _list_ *next;
struct _list_ *prev;
float distance;
}
Now i am making a push_front function and it works great. I get the result that i am looking for. But now i am making pop_front function and something is missing.
The function should return the distance and then remove that list from the linked list but i can't make it do it.
here is the code that i wrote
int pop_front(list** header)
{
float number = (*header)->data;
list *head = *header;
list *remove = head;
// This should check if the pointer is pointing at the first element
while (head->prev != NULL) {
head = head->prev;
}
if (head) {
head = head->next;
free(remove);
remove = head;
remove->prev = NULL;
//if i remove the code below then i get this error
//*** Error in `./double_ended_queue.out': double free or
//corruption (fasttop): 0x0000000001d5a050 ***
//Pop up: 3 pointer: 3 Aborted (core dumped)
*header = *remove;
//And with this code i get a Segmentation fault (core dumped
return number;
}
return 0;
}
Any help would be great, thank you.
P.S. checked all the linked list question here and none helped.

Where are you all getting this homework from? The API sux. Here, someone else did have almost the same homework (link pointing to my answer, which has many issues left): Pointer Dequeue - pointer training
Anyways:
Do you want to return int or float? The element data is type float, your variable "number" too, but your function returns int.
int pop_front(list** header)
{
float number = (*header)->data;
so, here you get the value of the element you're trying to remove, but then ...
list *head = *header;
list *remove = head;
// This should check if the pointer is pointing at the first element
while (head->prev != NULL) {
head = head->prev;
}
... you actually SEARCH for the element to remove.
Obviously, you have to do it the other way round:
int pop_front(list** header)
{
list * head = *header;
while (head->prev) head = head->prev;
now, you should check, weather you need to adjust the *header pointer (and do it right away):
if (*header == head) {
*header = head->next;
}
the only thing to do now is to remove the object from the list, get it's value and free it's memory before return.
head->next->prev = NULL;
float retval = head->data;
free(head);
return retval;
}
As exercise left to you: Make sure, that an empty list doesn't crash ;)
/edit: This will also crash for removal of the last element, so you have two exercises left ;)

Related

C linked list define how to reimplement a list

Hi this is probably a stupid question to ask with a simple solution but I just can't find an answer in the internet.
So I was exercising for an exam and worked on an assignment. The program has the job to find out what the value in the center of a linked list is (if the length of the list is an odd number)
The structdef is:
typedef struct IntList IntList;
struct IntList {
int value;
IntList* next;
};
and my exact problem right now is that I get a segmentation fault when I try using:
list = list->next;
I want to go step by step in a loop to go to the wished list at the nth position (the center) of the linked list.
Someone knows how I have to rewrite this? If you need more Information to help just say so and I will explain more.
With that function I check the length of the list and in my other function I have a loop which only goes to the mid of the length.
int length_list(IntList* list) {
int n = 0;
for(IntList* node = list; node != NULL; node = node->next) n++;
return n;
}
After this loop ends for(IntList* node = list; node != NULL; node = node->next) n++; you surely have node==NULL.
That is not immediatly a problem.
But depending on what you do with the value of n which you return you might have an off-by-one problem. E.g. in a list with exactly one entry (1 is odd after all), the attempt to use a value which is 1 too high could result in an attempt to access a non-existing node.
Because of this I suspect that your problem might be solved by changing the loop to
for(IntList* node = list; node->next != NULL; node = node->next) n++;, so that it ends on the last existing node, instead of behind. The return value will be lower, whatever you do with it will be "more-careful".
That or try something similar with the small code fragment you show and ask about, list = list->next; only do that if the next is not NULL, not if only list is not NULL.

Creating and displaying linear linked list in C(Recursively)

I'm trying to creating linear linked list recursively with c language,
but keep sticking from here and the code is not working with the error "Linker Tools Error LNK2019". Sadly i can't understand what's the matter. Here is my code.
Thanks for your big help in advance.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char num; //Data of the node
struct node *nextptr; //Address of the next node
};
typedef struct node element;
typedef element *link;
link head;
void displayList(); // function to display the list
int main()
{
char s[] = "abc";
link stol(s);
{
link head;
if (s[0] == '\0')return(NULL);
else {
head = (link)malloc(sizeof(element));
head->num = s[0];
head->nextptr = stol(s + 1);
return(head);
}
}
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf("-------------------------------------------------------------\n");
displayList();
return 0;
}
void displayList()
{
link tmp;
if (head == NULL)
{
printf(" List is empty.");
}
else
{
tmp = head;
while (tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}
You redefine a link object called head in your main() function. It hides the global head variable.
Removing the definition inside main would fix your problem, but you should consider passing a link* as a parameter to your displayList function in any case.
I've just noticed this statement return(head); in main(). You program exits prematurely as a result as well.
Everytime I look at your app, I find more issues. If I were you, I'd start by creating a function that adds a node to the list. It's much easier to add new nodes to the front of the list, so you should try that first. Try adding to the tail once you get this running. Adding to the tail is very similar, but you have to 'walkthe list first to get to the last element, exactly as you already do indisplayList()` Another way is keeping the address of the last node* you've added to the list. Like I said, it adds a bit of complexity, so get it working with addToHead first.
void addToHead(link* l, node* n)
{
n->nextptr = l->nextptr;
l->nextptr = n;
}
in your main, you can allocate one new node at a time, as you already do with malloc(). Initialize its contents num with an integer, and let addToHead deal with the pointer stuff. Your use of pointers is terrible, but lists are quite easy, and addToList pretty much shows what can and what should be put in pointers - namely other pointers.
You can remove almost everything in main() before the first printf. You'll have to
start loop:
write a prompt so the user knows what to do using printf()
read input from user using scanf("%d", &n), or equivalent.
break from the loop if user enters a negative value.
malloc() a new node
set its data num = n
call addToHead to add the node.
Loop until user enters an empty string, or -1.
That should take about 8 to 10 lines of code. if in doubt, you will easily find documentation on scanf, with google or on http://en.cppreference.com/w/c.

Segfault when accessing next node in singly linked list

I'm trying to just reverse a singly linked list, but with a bit of a twist. Rather than having the pointer to the next node be the actual next node, it points to the pointer in that next node.
struct _Node
{
union
{
int n;
char c;
} val;
void *ptr; /* points to ptr variable in next node, not beginning */
int var;
};
typedef struct _Node Node;
I know how to reverse a normal singly linked list and I think I have the general idea of how to go about solving this one, but I'm getting a segfault when I'm trying to access head->ptrand I don't know why.
Node *reverse(Node *head)
{
Node * temp;
Node * prev = NULL;
while(head != NULL)
{
temp = head->ptr + 4; /* add 4 to pass union and get beginning of next node */
head->ptr = prev;
prev = head;
head = temp;
}
return prev;
}
Even if I try and access head->ptr without adding 4, I get a segfault.
The driver that I have for this code is only an object file, so I can't see how things are being called or anything of the sort. I'm either missing something blatantly obvious or there is an issue in the driver.
First, I'll show you a major problem in your code:
while (head) // is shorter than while(head != NULL)
{
// Where does the 4 come from?
// And even if: You have to substract it.
// so, definitively a bug:
// temp = head->ptr + 4; /* add 4 to pass union and get beginning of next node */
size_t offset_ptr = (char*)head->ptr - (char*)head;
// the line above should be moved out of the while loop.
temp = head->ptr - offset_ptr;
Anyways, your algorithm probably won't work as written. If you want to reverse stuff, you are gonna have to work backwards (which is non-trivial in single linked lists). There are two options:
count the elements, allocate an array, remember the pointers in that array and then reassign the next pointers.
create a temporary double linked list (actually you only need another single reversely linked list, because both lists together form a double linked list). Then walk again to copy the next pointer from your temporary list to the old list. Remember to free the temporary list prior to returning.
I tried your code and did some tweaking, well in my opinion your code had some logical error. Your pointers were overwritten again and again (jumping from one node to another and back: 1->2 , 2->1) which were leading to suspected memory leaks. Here, a working version of your code...
Node *reverse(Node *head)
{
Node *temp = 0;
//Re-ordering of your assignment statements
while (head) //No need for explicit head != NULL
{
//Here this line ensures that pointers are not overwritten
Node *next = (Node *)head->ptr; //Type casting from void * to Node *
head->ptr = temp;
temp = head;
head = next;
}
return temp;
}

Unable to reverse a linked list

I was trying to reverse a linked list, however whenever I execute the following function, I get only the last element. For example, if the list contained 11,12,13 earlier. After executing the function, it contains only 13. Kindly point out the bug in my code
void reverselist() {
struct node *a, *b, *c;
a = NULL;
b = c = start;
while (c != NULL) {
c = b->next;
b->next = a;
a = b;
b = c;
}
start = c;
}
Doesn't your loop guard insure that start is null?
If you aren't using start to identify the first element of the list, then the variable you ARE using is still pointing to what WAS the first element, which is now the last.
c is a helper pointer.
void reverselist()
{
struct node *a, *b, *c;
a=NULL;
b=start;
while(b!=NULL)
{
c=b->next
b->next=a;
a=b
b=c
}
start=a;
}
// You should assume that Node has a Node* called next that
// points to the next item in a list
// Returns the head of the reversed list if successful, else NULL / 0
Node *reverse( Node *head )
{
Node *prev = NULL;
while( head != NULL )
{
// Save next since we will destroy it
Node *next = head->next;
// next and previous are now reversed
head->next = prev;
// Advance through the list
prev = head;
head = next;
}
return previous;
}
I would have made a prepend function, and done the following:
struct node* prepend(struct node* root, int value)
{
struct node* new_root = malloc(sizeof(struct node));
new_root->next = root;
return new_root;
}
struct node* reverselist(struct node* inlist)
{
struct node* outlist = NULL;
while(inlist != NULL) {
struct node* new_root = prepend(outlist, inlist->value);
outlist = new_root;
inlist = inlist->next;
}
return outlist;
}
Have not tested this, but guess you grasp the idea of it. Might be just your variable names, which don't describe anything, but I think this approach is cleaner, and easier to understand what actually happens.
EDIT:
Got a question why I don't do it inplace, so I'll answer it here:
Can you do it inplace? Are you sure you don't wish to keep the
original list?
Do you need to do it inplace? Is the malloc to time consuming/is this a performance critical part of your code? Remember: premature optimization is the root of all evil.
Thing is, this is a first implementation. It should work, and not be optimized. It should also have a test written before this implementation is even thought of, and you should keep this slow, un-optimized implementation until the test passes, and you have proved that it's to slow for your use!
When you have a passing unit test, and proven the implementation to be to slow, you should optimize the code, and make sure it still passes the test, without changing the test.
Also, is it necessary inplace operations which is the answer? What about allocating the memory before reverting it, this way you only have one allocation call, and should hopefully get a nice performance boost.
This way everyone is happy, you have a cleaner code and avoid the risk of having Uncle Bob showing up at your door with a shotgun.

Segmentation fault in a function to reverse a singly linked list recursivley

I am implementing a function to recursively reverse a linked-list, but getting seg-fault.
typedef struct _node {
int data;
struct _node *next;
} Node, *NodeP;
NodeP recursiveReverseList(NodeP first){
if(first == NULL) return NULL;
if(first->next == NULL) return first;
NodeP rest = recursiveReverseList(first->next);
rest->next = first;
first->next = NULL;
return first;
}
Can you please help?
P.S. The iterative version is working fine though. Its not homework. Just practicing C.
Thank you all :)
The general recursive algorithm for this is:
Divide the list in 2 parts - first
node and rest of the list.
Recursively call reverse for the rest of the
linked list.
Link rest to first.
Fix head pointer
You are doing steps 1 and 2 correctly but I guess you've messed up in steps 3 and 4. I would suggest you try this:
NodeP recursiveReverseList(NodeP first){
if(first == NULL) return NULL; // list does not exist.
if(first->next == NULL) return first; // list with only one node.
NodeP rest = recursiveReverseList(first->next); // recursive call on rest.
//rest->next = first; CHANGE THIS
first->next->next = first; // make first next to the last node in the reversed rest.
first->next = NULL; // since first is the new last..make its next NULL.
//return first; CHANGE THIS
return rest; // rest now points to the head of the reversed list.
}
(source: geeksforgeeks.org)
.
EDIT:
PS: I've not tested this. So try it and let us know :)
I've tested the above function and seems to work as expected. You can try the program here:
http://ideone.com/bQXAV
#Unicornaddict has already posted a correct algorithm.
But, if you are still getting segmentation fault, I suspect you are making some mistake in calling the function from main.
Correct:
head->next = recursiveReverseList(head->next);
Explanation:
Pass head->next to the recursive function. If you pass head, it will do something like
Before call:
head ---> A ---> B ---> C
After call:
head <--- A <--- B <--- C
which will make head point to NULL and A point to head
After passing head->next as argument, state of the list is:
head ---> A <--- B <--- C
So, you need to make head point to rest (C in this case).
Your algorithm seems to be wrong. You need to return the pointer to the head of the new list, but you are returning the pointer to the last item.
Indeed, you perhaps need both of them: a pointer to the head and the pointer to the last item.
i think
rest->next = first;
should be
first->next->next = first;

Resources