C programing: How to pop last element on linked list? - c

I am beginner programer and one week ago i was introduced to linked list however I'm still struggling to wrap my head around this.
Currently trying to write a function that will help me remove last element from the linked list. I would appreciate some explanation what am i doing wrong here. Thank You for any suggestions.
I'm not allowed to touch or modify current structs
Here is my structs:
typedef struct node {
ElemType val;
struct node *next;
} NODE;
struct list_struct {
NODE *front;
NODE *back;
};
And heres my current code:
if list is empty, we do nothing and return arbitrary value
otherwise, the last element in the list is removed and its
value is returned.
ElemType lst_pop_back(LIST *l) {
NODE * p = l->front;
NODE * trail = l->front;
if( p == NULL) return 0;
if( lst_len(l) == 1){
free(p);
l->front = NULL;
l->back = NULL;
}
else{
p=p->next;
while( p != NULL){
if( p->next == NULL) free(p);
trail = trail->next;
p=p->next;
}
trail= trail->next;
trail->next= NULL;
}
return 0;
}
I'm using Xcode on MAC and the error that i get is: Thread 1: EXC_ACCESS(code=1, address=0x8)

The XCode error EXC_BAD_ACCESS(code=1, address=0x8) means that somebody tries to access unaccessable memory. XCode's boundary checks are said to be good, so let's trust them. It is a bit sad that the OP doesn't tell us the exact line-number but one can guess. I would concur with Katerina B. here and assume the same lines as the culprit.
In detail:
ElemType lst_pop_back(LIST * l)
{
// p and trail point to the first node
NODE *p = l->front;
NODE *trail = l->front;
if (p == NULL)
return 0;
if (lst_len(l) == 1) {
free(p);
l->front = NULL;
l->back = NULL;
} else {
p = p->next;
// Now: trail->next points to the old p
// and p to p->next, that is: trail points
// to the node before p
// while trail is not the last node
while (p != NULL) {
// if p is the last node
if (p->next == NULL){
// release memory of p, p points to nowhere from now on
free(p);
}
// Following comments assume that p got free()'d at this point
// because trail points to the node before p
// trail->next points to the node p pointed to
// before but p got just free()'d
trail = trail->next;
// p got free()'d so p->next is not defined
p = p->next;
}
// assuming p got free()'d than trail->next is one step
// further into unknown, pardon, undefined territory
trail = trail->next;
trail->next = NULL;
}
return 0;
}

I think the error you're getting happens when you try to access something that's already been deallocated. You're doing that here:
if( p->next == NULL) free(p);
trail = trail->next;
p=p->next;
Since the list structure contains a back pointer, I'd recommend using that to help you. Maybe let p move through the list until p->next points to the same thing as the list's back pointer, then make p->next null.
Also, should the function POP or REMOVE from the list? Your question says removing but the function is named lst_pop_back. If you're poping, you'll need to return the last value too.

Related

Doublind nodes linked list

I need to double every node in a linked list, the doubled nodes should be right after the copied node.
The function got the list.beg as parameter.
while (p != NULL)
{
q = p;
q->next= p->next;
p->next= q;
p = q->next;
}
For some reason the loop never ends.
You are just doing q = p;, so you're creating a node that links back to itself. That is, what you're doing is equivalent to:
p->next = p;
You have to allocate a new node for q.
It's a little difficult to be sure without the struct definition, but, here's some refactored code:
while (p != NULL) {
q = malloc(sizeof(*q));
// NOTE: this only works if the node does _not_ have a pointer to some data
// otherwise, a "deep copy" is required
*q = *p;
p->next = q;
p = q->next;
printf("%i\n", q->data.number);
}
When I mentioned "deep copy" above, it would apply if the node had an element such as:
const char *str;
Where str was created initially via (e.g.):
p->str = strdup(buf);
possibly as part of an fgets(buf,sizeof(buf),stdin); loop.
Then, in the duplication code, after the *q = *p;, we'd need:
q->str = strdup(p->str);

Issues with linked list and pointers (C)

I am writing a C program to sort a linked list according to the largest values. I met an issue whereby the program just hangs when the program reached "prevPtr->next = headPtr".
I want the prevPtr->next to equate to headPtr, if the sum of prevPtr is larger than the sum of headPtr, however the program just hangs there.
compareNodes() function is used to compare the nodes to see if newNode has the same name as any other structs in the linked list, then it will add in the sum.
sortSimilarNodes() function is used to sort the nodes according to the sum of each struct.
The struct is here below:
struct purchase {
char name[30];
double sum;
struct purchase * next;
} ;
LOG * compareNodes(LOG * headPtr, char * name, char * price){
.
.
.
while (curPtr != NULL) {
if (strcmp(newNode->name, curPtr->name)==0) {
curPtr->sum += newNode->sum;
free(newNode);
similar = 1;
break;
}
//advance to next target
prevPtr = curPtr;
curPtr = curPtr->next;
}
/*if (curPtr == NULL){
if(strcmp(newNode->name, prevPtr->name)==0){
prevPtr->sum += newNode->sum;
free(newNode);
similar = 1;
}
}*/
if (similar == 1){
headPtr = sortSimilarNodes(curPtr, headPtr);
}
else{
headPtr = sortNodes(newNode, headPtr);
}
return headPtr;
}
LOG * sortSimilarNodes(LOG * newPtr, LOG * headPtr){
LOG * curPtr;
LOG * prevPtr;
if(headPtr->sum < newPtr->sum){
newPtr->next = headPtr;
return newPtr;
}
prevPtr = headPtr;
curPtr = headPtr->next;
while (curPtr == NULL){
}
while (curPtr != NULL){
if(strcmp(curPtr->name, newPtr->name)==0){
break;
}
prevPtr = curPtr;
curPtr = curPtr->next;
}
return headPtr;
}
This is the output of the program.
Thank you!
It's hard to tell from your code, because you haven't posted all of it, but you seem to have some misconceptions about linked lists. In particular:
There is no need for new nodes unless you really add new nodes to the list. That also means that you don't call malloc except when adding nodes. (There's no malloc in your code, but a suspicious free in your comparison function. Comparing does not involve creating or destroying anything; it just means to look what is already there.)
A corollary to the first point is that there should be no nodes in an empty list, not even dummy nodes. An empty list is a list whose head is NULL. Make sure that you initialise all head pointers before creating a new list:
LOG *head = NULL; // empty list
When you sort the list, the order of the list has changed and the old head is invalid. You cater for that by returning the new head:
head = sort(head);
But that seems redundant and it also seems to imply that the two pointers can be different. That's not the case, because the old pointer will point somehwre in the sorted list, not necessarily at its head. It's probably better to pass the head pointer's address in order to avoid confusion:
sort(&head);
Sorting linked lists can be tricky. One straightforward way is selection sort: Find the node with the highest value, remove it from the original list and add it at the front of a new list. Repeat until there are no more nodes in the original list.
Adding a new node n at the front of a list given by head is easy:
n->next = head;
head= n;
Adding a new node at the end of a list that is given by head is a bit more involved:
LOG **p = &head;
while (*p) p = &(*p)->next;
*p = n;
n->next = NULL;
Here, p is the address of the pointer that points to the current node, *p. After walking the list, that address is either the address of the head node (when the list is empty) or the address of the next pointer of the precedig node.
You could achieve something similar by keeping a prev pointer, but the pointer-to-pointer solution means that you don't have to treat the cases where there is no previous node specially at the cost of some extra & and * operators.
With that, your sorting routine becomes:
void sortByName(LOG **head)
{
LOG *sorted = NULL;
while (*head) {
LOG **p = head; // auxiliary pointer to walk the list
LOG **max = head; // pointer to current maximum
LOG *n; // maximum node
while (*p) {
if (strcmp((*p)->name, (*max)->name) > 0) max = p;
p = &(*p)->next;
}
n = *max;
*max = (*max)->next;
n->next = sorted;
sorted = n;
}
*head = sorted;
}
If you want to sort by sum, change the comparison to:
if ((*p)->sum > (*max)->sum) max = p;
Call the function like this:
LOG *head = NULL;
insert(&head, "apple", 2.3);
insert(&head, "pear", 1.7);
insert(&head, "strawberry", 2.2);
insert(&head, "orange", 3.2);
insert(&head, "plum", 2.1);
sortByName(&head);
print(head);
destroy(&head);
with the insert, destroy and print functions for completeness:
void insert(LOG **head, const char *name, double sum)
{
LOG *n = malloc(sizeof(*n));
if (n) {
snprintf(n->name, sizeof(n->name), "%s", name);
n->sum = sum;
n->next = *head;
*head = n;
}
}
void destroy(LOG **head)
{
LOG *n = *head;
while (n) {
LOG *p = n;
n = n->next;
free(p);
}
*head = NULL;
}
void print(LOG *l)
{
while (l) {
printf("%s: %g\n", l->name, l->sum);
l = l->next;
}
puts("");
}

insert an element at end node of link list in c

i want to add a node at end of link list. so i made a method for the same and it gives expected result. But i am not sure about this program is correct or not. please see program wether it is correct or not.
node *insert_end_node(node *nd, int value) {
node *tmp, *p;
tmp = (node *)malloc(sizeof(node *));
tmp->data = value;
tmp->next = NULL;
p = nd;
while (p->next != NULL) {
p = p->next;
}
p->next = tmp;
// nd =tmp;
return nd;
}
Thanks in advance
Two things:
When you accept a pointer as a parameter, you should always check to see if it is NULL. In your case, if nd == NULL, then you will try to access NULL->next and your program will likely crash.
When you call tmp = (node *)malloc(sizeof(node*)), you want to allocate enough memory for a node, not for a node pointer. The correct code is tmp = (node *)malloc(sizeof(node)). An even better option is to write tmp = (node *)malloc(sizeof(*tmp)), because if you decide to change tmp's type, the allocation will still work.

how to implement linked list deletion?

#include<stdio.h>
struct node {
int info;
struct node *next;
};
typedef struct node *nodeptr;
nodeptr i;
nodeptr q;
nodeptr p;
nodeptr *plist;
nodeptr getnode(void)
{
nodeptr p;
p = (nodeptr) malloc(sizeof(struct node));
return p;
}
void freenode(nodeptr p)
{
free(p);
}
int main()
{
int i;
nodeptr *k;
int a;
int *px;
int r;
nodeptr end;
nodeptr s;
nodeptr start;
p = getnode();
q = getnode();
q = start;
p = end;
for (i = 0; i < 6; i++) {
printf("enter value");
scanf("%d", &r);
p = getnode();
p->info = r;
q->next = p;
q = q->next;
}
q = start;
while ((q->next) != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
scanf("%d", &a);
end = getnode();
end->info = a;
end->next = NULL;
for (q = start; q->next != NULL; q = q->next)
;
q->next = end;
q = start;
while ((q->next) != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
for (q = start; q->next->next != NULL; q = q->next)
;
freenode(q->next);
q->next = NULL;
q = start;
while (q->next != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
return 0;
}
in this program alist is made and an element is inserted at the end
in this the element is getting deleted but the list is not shown properly
only last two elements are getting displayed
please help so as to show the whole list with element deleted
There is a lot wrong, undortunately. As WhozCraig said, there's a lot of other posts on this topic, so you should have probably searched a little more before posting. But since you have, let's walk through some of the issues together.
nodeptr i;
nodeptr q;
nodeptr p;
nodeptr *plist;
Here you are declaring a ton of global variables, most with bad names. What's i? What's p? What's q? Further down, you redeclare variables with the same names. Some with the same type, others with different type. This make it confusing to know which variable you're referencing.
Generally speaking, avoid global variables and choose descriptive names. In this case, you can just get rid of i, p and q.
Also, you never initialize plist to anything; you should get into the habit of initializing variables to some sane default value. In this case, NULL could be appropriate, but since you do not use the variable at all it can be deleted.
nodeptr getnode(void)
{
nodeptr p;
p = (nodeptr) malloc(sizeof(struct node));
return p;
}
This is good, however in C you should not cast the result of malloc to a particular type as this is considered bad form and can cause subtle and hard to detect bugs. Just assign the return from malloc directly.
Secondly, you never check to make sure that malloc succeeded. Granted, it's unlikely that it would fail in your simple program, but you should get in the habit of checking the return value of functions that can fail.
And you should probably initialize the allocated memory to some default value, because the memory returned to you by malloc is full of junk. In this case, something like this seems appropriate:
if(p) /* only if we allocated memory. */
memset(p, 0, sizeof(struct node));
There are times when you could skip this, but clearing the memory is a sane default practice.
void freenode(nodeptr p)
{
free(p);
}
This is also fine, but you should consider verifying that p is not NULL before you call free. Again, this comes down to robustness, and it's a good habit to get into.
int main()
{
int i;
nodeptr *k;
int a;
int *px;
int r;
nodeptr end;
nodeptr s;
nodeptr start;
Again, here we have a lot of unitialized variables, but at least some of the names are a bit better. But notice what happens:
You declare a variable called i of type int. But you've already declared a global variable called i that is of type nodeptr. So now, the variable in the local scope (the int) shadows (that is, it hides it) the global variable. So inside main the name i refers to the int. This just adds to the confusion when someone is reading your program.
p = getnode();
q = getnode();
OK... so, over here you allocate two new nodes and make p and q point to those nodes. So far so good.
q = start;
p = end;
Oops... now this is a problem. We now make p and q point to wherever start and end respectively point to.
And where do those point to? Who knows. Both start and end are unitialized, so they can point to anything. From this point on, your program exhibits undefined behavior: this means that anything can happen. Most likely, in this case, it will just crash.
Unfortunately from here on down, things become a lot more confusing. Instead of trying to explain everything, I'll just give some general commentary.
for (i = 0; i < 6; i++) {
printf("enter value");
scanf("%d", &r);
p = getnode();
p->info = r;
q->next = p;
q = q->next;
}
This loop is supposed to read 6 integers and put them in our linked list. This seems like a simple thing to do but there are issues.
First of all, you never check the return of scanf to know if the input operation succeeded. As I said before, you should always check the return value of functions that can fail and handle the failure accordingly. But in this case, let's ignore that rule.
A big problem is that q points to a random location in memory. So we're in undefined behavior land.
Another big problem is that there are two cases to consider: when the list is empty (i.e. the first time we're adding a number to the list when i == 0) and when the list is not empty (i.e. every other time). The behavior in those two cases differs. When i == 0 we can't just blindly set q->next, because even if q didn't point to a random location, there would, conceptually, be no q the way it's used here.
What we need here is some extra logic: if this is the first node that we are creating, set q to point to that node. Otherwise, set q->next to that node and then do q = q->next.
Please note, also, that you never set p->next anywhere, which would cause your list to not be NULL-terminated (something that you rely on here and in other loops). The memset fix in getnode corrects this problem, but generally you should make sure that if your code expects a particular behavior ("an unlinked node's next pointer points to NULL; lists are NULL-terminated") you should have code to ensure that behavior.
q = start;
Again, here, we reset q to point to start which is still uninitialized and points to garbage.
while ((q->next) != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
This is a classic printing loop. Nothing wrong here, per se, although I think that stylistically, those parentheses around q->next are overkill and make reading the code a little more difficult than it has to be. My guideline would be to only add parentheses when they're necessary to override the default evaluation order of C or when the parentheses helps to visually explain to the reader how to group the expression in his head when mentally parsing the code.
scanf("%d", &a);
end = getnode();
end->info = a;
end->next = NULL;
This is fine, except for the error-checking issue with scanf, although you don't prompt the user to enter a number. But you correctly and explicitly make end->next point to NULL which is great.
for (q = start; q->next != NULL; q = q->next)
;
Again, the problem here is that q is set to start which, unfortunately, still points to garbage.
q->next = end;
q = start;
while ((q->next) != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
This is the second time you've had to type this code to print the list. Generally, you should avoid code duplication. If you find that you need a particular code block in more than one place, it makes sense to split it out into a function and use the function. This makes understanding and maintaining the code easier.
for (q = start; q->next->next != NULL; q = q->next)
;
This loop is tricky to understand because of the q->next->next bit. Ask yourself "if I'm reading this, am I immediately sure that q->next can't ever be NULL?" If you aren't, then you really ought to rewrite this loop.
freenode(q->next);
q->next = NULL;
q = start;
Again, q is made to point to start which is unitialized. But hey, if we haven't crashed yet... ;)
while (q->next != NULL) {
printf("n%d", (q->next)->info);
q = q->next;
}
And again... this should really be a function.
return 0;
}
For a better implementation I refer you to one of the many other questions asked here (just search for "linked list delete". The implementation in this question by Khalid Waseem could also be of help, but it's not very documented, so you will have to carefully study and analyze the code to make sure that you understand it.
See below implementation for a better understanding.
struct node {
int info;
struct node *next;
};
typedef struct node node;
//Function to print a given single linked list.
void print_list(node *start)
{
//Check if the given list is empty.
if(start == NULL)
printf("List Empty!!!");
else
{
printf("Current List:");
//Visit each node one by one
while(start != NULL)
{
printf(" %d", start->info);
start = start->next;
}
}
}
//Function to insert a node at end of single linked list with given data
node* insert_at_end(node *start, int data)
{
node *ptr;
//Create a new node and assign memory using malloc
node* new_node = (node*)malloc(sizeof(node));
if(new_node != NULL)
{
//Initialize new node with data.
new_node->info = data;
new_node->next = NULL;
}
else
{ //Panic
printf("\nMemory not allocated. Insertion failed!!!");
return start;
}
//If input list is empty. then new_node becomes the first node of link list.
if(start == NULL)
return new_node;
else
{
//travel to the last node of list
ptr = start;
while(ptr->next != NULL)
ptr = ptr->next;
//Attach the newly created node at end of list.
ptr->next = new_node;
return start;
}
}
//Delete a node from the end of a Single linked list
node* delete_at_end(node *start)
{
node *ptr;
//If input list is empty. nothing to delete just return.
if(start == NULL)
return NULL;
//Just one node in the given linked list.
else if(start->next == NULL)
{
//Free the memory assigned to the node.
free(start);
return NULL;
}
else
{ //Travel to the second last node of the linked list.
ptr = start;
while(ptr->next->next != NULL)
ptr = ptr->next;
//free the last node.
free(ptr->next);
ptr->next = NULL;
return start;
}
}
int main()
{
int i, data;
node *Head_node = NULL;
for(i = 1; i<=5 ; i++)
{
printf("\nEnter node %d :", i);
scanf("%d", &data);
// Insert at End
Head_node = insert_at_end(Head_node, data);
// Print current List
print_list(Head_node);
}
for(i = 5; i>=1 ; i--)
{
printf("\nDeleting node %d :\n", i);
// Delete at End
Head_node = delete_at_end(Head_node);
// Print current List
print_list(Head_node);
}
return 0;
}

reverse linked list recursively - different function signature

There are many posts with probably with same question but the problem says it has to be done by
node* reverseList (node * lh)
{
if(lh==NULL)............ ;
else if (lh->next==NULL)...........;
else ...........;
}
the three blanks must be filled
the first two are simply
return NULL
and
return lh
repectively
one way could be just to go down and reverse the pointers but in that case how can i keep the tail intact even after backtracking? is it possible at all?
The trick to solving recursive problems is to pretend that you are done already. To solve this homework by yourself, you need to answer three questions:
How do you reverse an empty list? (i.e. a list with lh set to NULL)?
How do you reverse a list with only one item?
If someone could reverse all items on the list except the initial one for you, where do you add the first item from the initial list to the pre-reversed "tail" portion of the list?
You answered the first two already: NULL and lh are the right answers. Now think of the third one:
else {
node *reversedTail = reverseList(lh->next);
...
}
At this point, reversedTail contains pre-reversed tail of your list. All you need to do is set lh->next to NULL, add it to the back of the list that you are holding, and return reversedTail. The final code looks like this:
else {
node *reversedTail = reverseList(lh->next);
node *p = reversedTail;
while (p->next) p = p->next;
p->next = lh;
lh->next = NULL;
return reversedTail;
}
I think this answers it:
node *reverseList(node *lh)
{
if (!lh) return NULL;
else if (!lh->next) return lh;
else {
node *new_head = reverseList(lh->next);
lh->next->next = lh;
lh->next = NULL;
return new_head;
}
}
It returns the head of the reversed list, i.e. the tail of the original list.
head = reverse_list(head);
Below is an API which does the reversal of a Single linked list, this one of the best algo that i have seen:
void iterative_reverse()
{
mynode *p, *q, *r;
if(head == (mynode *)0)
{ return;
}
p = head;
q = p->next;
p->next = (mynode *)0;
while (q != (mynode *)0)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head = p;
}

Resources