Deleting front node from a Singly Linked List in C - c

I am trying to delete from a Singly Linked List, however, when I try to delete from the first element, it prints garbage. I think the problem comes from the delete_node function, however, I tried everything and I cannot figure it out.
#include <stdio.h>//prinf
#include <stdlib.h>//alloc mallco callo
typedef struct node node;
struct node{
int number;
node *next;
};
node *new_node(int num){
node *n= (node*) malloc(sizeof(node));
n->number=num;
n->next=NULL;
return n;
}
void node_free_all(node *n){
if(n != NULL){
node_free_all(n->next);
free(n);
}
}
void print_nodes(node *n){
if(n != NULL){
print_nodes(n->next);
printf("Number is: %d\n",n->number);
}
}
void delete_node(node *n, int num){
node *rmNode= (node*)malloc(sizeof(node));
//delete first
if( n!= NULL && n->number==num){
rmNode = n;
n=n->next;
free(rmNode);
}
//all but first
while(n != NULL){
if(n->next != NULL && n->next->number == num){
rmNode= n->next;
n->next = rmNode->next;
free(rmNode);
break;
}
n=n->next;
}
}
int main(){
int i;
node *head= (node*) malloc(sizeof(node));
node *curr;
head=NULL;
for(i=1;i<=10;i++) {
curr = new_node(i);
curr->next =head;
head=curr;
}
printf("Everything:\n");
print_nodes(head);
printf("Deleting 1:\n");
delete_node(head,1);
print_nodes(head);
printf("Deleting 5:\n");
delete_node(head,5);
print_nodes(head);
printf("Deleting 2:\n");
delete_node(head,2);
print_nodes(head);
printf("Deleting 3:\n");
delete_node(head,3);
print_nodes(head);
printf("Deleting 10:\n");
delete_node(head,10);
print_nodes(head);
printf("Deleting 9:\n");
delete_node(head,9);
print_nodes(head);
node_free_all(head);
// node_free_all(list);
return 0;
}
What am I doing wrong?

You don't need to allocate memory to rmNode. Plus you need to pass the reference of head pointer to the function delete_node because every time you are updating the list and if you have to delete first element of list, then in this case head pointer also got updated.
struct node
{
int number;
node *next;
};
void delete_node(struct node** head_ref, int num)
{
struct node* temp;
struct node* current = (*head_ref);
//delete first
if( current != NULL && current->number == num)
{
temp = current;
current = current->next;
free(temp);
(*head_ref) = current;
}
else
{
//all but first
while(current != NULL)
{
if(current->next != NULL && current->next->number == num)
{
temp = current->next;
current->next = temp->next;
free(temp);
break;
}
current = current->next;
}
}
}

here's a version that removes all items that matches num, and always update the head item.
void delete_node(node** head_ref, int num)
{
node* temp;
node* last = 0;
node* current = *head_ref;
while(current)
{
if( current->number == num )
{
temp = current;
if( current == *head_ref )
current = (*head_ref) = current->next;
else
current = last->next = current->next;
free(temp);
} else {
last = current;
current = current->next;
}
}
}
You have to call it like delete_node(&head,1);
because it needs an address to the head item to be able to change it

Related

Segmentation fault (core dumped) in Linked List using C

I want an array of linked List and obviously each linked should have separate head node. Initially, as an example, I am starting with one array element. I am storing linkedlist into current[0] . But it is giving segmentation fault. If I use Node *current it will create a list and working fine. But, I want to store the list within array. What is wrong with the code ?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *current[20];
void insert_beg_of_list(Node *current[0], int data);
void print_list(Node *current[0]);
void insert_beg_of_list(Node *current[0], int data) {
//keep track of first node
Node *head = current[0];
while(current[0]->next != head) {
current[0] = current[0]->next;
}
current[0]->next = (Node*)malloc(sizeof(Node));
current[0] = current[0]->next;
current[0]->data = data;
current[0]->next = head;
}
void print_list(Node *current[0]) {
Node *head = current[0];
current[0] = current[0]->next;
while(current[0] != head){
printf(" %d ", current[0]->data);
current[0] = current[0]->next;
}
}
int main() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = head;
int data = 0 ;
int usr_input = 0;
int i;
int m;
int j;
scanf("%d", &usr_input);
for (i=0; i<usr_input; i++) {
scanf("%d", &data);
insert_beg_of_list(head, data);
}
printf("The list is ");
print_list(head);
printf("\n\n");
return 0;
}
I think you have mixed the global array current's use. Change your code to this :
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert_beg_of_list(Node *current, int data);
void print_list(Node *current);
void insert_beg_of_list(Node *current, int data) {
//keep track of first node
Node *head = current;
while(current->next != head) {
current = current[0]->next;
}
current->next = malloc(sizeof(Node));
if (current->next == NULL)
return;
current = current->next;
current->data = data;
current->next = head;
}
void print_list(Node *current) {
Node *head = current;
current = current->next;
while(current != head){
printf(" %d ", current->data);
current = current->next;
}
}
int main() {
Node *current[20];
Node *head = malloc(sizeof(Node));
if (head == NULL)
return;
head->next = head;
int data = 0 ;
int usr_input = 0;
int i;
int m;
int j;
scanf("%d", &usr_input);
for (i = 0; i < usr_input; i++) {
scanf("%d", &data);
insert_beg_of_list(head, data);
}
//assign the newly created pointer to a place in the array
current[0] = head;
printf("The list is ");
print_list(head);
printf("\n\n");
return 0;
}
Keep in mind that the parameter current in your functions' prototypes and declarations is not the same as the array current created in your main function. I just left the name as it was.
NOTE : You should do something with head->next pointer, initialize it.
Also read this link on why not to cast the result of malloc and another one on why you should check its result.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert_beg_of_list(Node *current, int data);
void print_list(Node *current);
void insert_beg_of_list(Node *current, int data) {
//keep track of first node
Node *head = current;
while (current->next != head) {
current = current->next;
}
current->next = (Node*)malloc(sizeof(Node));
current = current->next;
current->data = data;
current->next = head;
}
void print_list(Node *current) {
Node *head = current;
current = current->next;
while (current != head) {
printf(" %d ", current->data);
current = current->next;
}
}
Node *NewList()
{
Node *newnode = (Node *)malloc(sizeof(Node));
newnode->next = newnode;
}
int main() {
Node *arrayofheads[20];
// We are using only arrayofheads[0] in this example
arrayofheads[0] = NewList();
int data = 0;
int usr_input = 0;
int i;
scanf("%d", &usr_input);
for (i = 0; i<usr_input; i++) {
scanf("%d", &data);
insert_beg_of_list(arrayofheads[0], data);
}
printf("The list is ");
print_list(arrayofheads[0]); printf("\n\n");
return 0;
}

Linked list insertion behaviour

I found some odd behaviour in my C code last night.
I have a few base functions for creating and manipulating C Linked Lists.
The behaviour of my insert at nth position is odd though.
The first version works fine, but the second version does not insert at all into the list. Am I missing something?
//This works fine
void insert_nth(struct node** head, int data, int n_pos){
if (n_pos == 0){
insert_top(head, data);
return;
}
struct node* current = *head;
for(int i = 0; i < n_pos - 1 ; i++){
if(current == NULL) return;
else current = current->next;
}
if(current == NULL) return;
insert_top(&(current->next), data);
}
//This doesn't insert at all
void insert_nth(struct node** head, int data, int n_pos){
if (n_pos == 0){
insert_top(head, data);
return;
}
struct node* current = *head;
for(int i = 0; i < n_pos ; i++){
if(current == NULL) return;
else current = current->next;
}
if(current == NULL) return;
insert_top(&(current), data);
}
Here are the rest of the functions I'm using for reference.
int main(){
struct node* head = NULL;
build_rand_list(&head);
list_print(&head);
return 0;
}
void list_print(struct node** head){
printf("List size is %d: List: ", list_length(head));
for(struct node* current = *head; current!= NULL; current = current->next)
printf("%d ", current->data);
printf("\n");
}
void build_rand_list(struct node** head){
//Assume head is NULL
assert(*head == NULL);
srand(time(NULL));
for (int i = 0; i < 10; i++){
int random_num = rand() % 11;
insert_end(head, random_num);
}
}
void insert_top(struct node** head, int data){
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
&(current) is the address of a local variable.
&(current->next) is the address of a pointer inside a node in the list.
Modifying the local variable current, which is what insert_top ultimately does, has no effect on the list's nodes.
For example if you pass the node with the value 2 to the insert_top function the result will be something like this
It seems like you don't handle the pointers correctly. For example there is no node that points to the new node you created.
A better implementation would be
void insert_nth(struct node *head, int data, int npos) {
struct node *current = head;
for (int i = 0; i < npos - 1; i++) {
current = current->next;
if (current == null) {
printf("%s\n", "Insert failed");
return;
}
}
struct node *new_node = (struct node *)malloc(sizeof(struct node *));
new_node->data = data;
new_node->next = current->next;
current->next = new_node;
return;
}
Where the head parameter is the actual head of the list.
The result will then me more satisfying. Hope this helps.

Deleting a node at a given position in Linked List

Given a singly linked list and a position, i am trying to delete a linked list node at a specific position.
CODE:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void printList(struct node* head_ref)
{
//struct node* head_ref = (struct node*)malloc(sizeof(struct node));
if(head_ref == NULL)
printf("The list is empty");
while(head_ref!=NULL)
{
printf("%d\n",head_ref->data);
head_ref = head_ref->next;
}
}
void insert_beg(struct node **head_ref,int new_data)
{
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void delete(struct node **head_ref,int position)
{
int i=1;
if(*head_ref == NULL)
return;
struct node *tails,*temp = *head_ref;
if(position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
while(temp->next!=NULL)
{
tails = temp->next;
temp = temp->next;
if(i == position)
{
tails->next = temp->next;
free(temp);
return;
}
i++;
}
}
int main()
{
struct node *head = NULL;
insert_beg(&head,36);
insert_beg(&head,35);
insert_beg(&head,34);
insert_beg(&head,33);
printList(head);
int position;
printf("Enter the position of the node u wanna delete\n");
scanf("%d",&position);
delete(&head,position);
printf("\n");
printList(head);
}
Whenever I am trying to delete a node above position 0, I am getting 0 in that specific position instead of nothing. Could I know where I am going wrong?
For eg my list is : 33 34 35 36
My Output: 33 0 35 36 (while attempting to delete node 1)
Valid Output: 33 35 36
The problem occurs due to this wrong statement
while(temp->next!=NULL)
{
tails = temp->next;
^^^^^^^^^^^^^^^^^^^
temp = temp->next;
In this case tails and temp are the same nodes. And if temp is deleted then you set the data member next of the deleted node to temp->next
if(i == position)
{
tails->next = temp->next;
^^^^^^^^^^^^^^^^^^^^^^^^^
Here tails is node that will be deleted.
You should change the data member next of the node before the deleted node. So the wrong statement should be updated like
while(temp->next!=NULL)
{
tails = temp;
^^^^^^^^^^^^^
temp = temp->next;
As for me then I would write the function the following way
int delete( struct node **head, size_t position )
{
struct node *prev = NULL;
size_t i = 0;
while ( i != position && *head != NULL )
{
prev = *head;
head = &( *head )->next;
++i;
}
int success = *head != NULL;
if ( success )
{
struct node *tmp = *head;
if ( prev == NULL )
{
*head = ( *head )->next;
}
else
{
prev->next = ( *head )->next;
}
free( tmp );
}
return success;
}
Into your delete function while loop tails and temp move forward a the same time starting fro the same address. The node is not deleted because you are always assigning the same value (in other words you are only confirm next pointer value each time).
That means that, after your cancellation, printout is UB due to the freed memory of one of the nodes.
Correcting your code:
void delete(struct node **head_ref,int position)
{
int i=1;
if(*head_ref == NULL)
return;
struct node *temp = *head_ref;
if(position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
struct node *tails = *head_ref;
while(temp->next!=NULL)
{
temp = temp->next;
if(i == position)
{
tails->next = temp->next;
free(temp);
return;
}
tails = tails->next;
i++;
}
}

sorting a singly linked list with quicksort after user input and then inserting a new node and resorting list

I have my code for the most part but having a rough go of it trying to get my quick sort function to work and sort through the actual link list created. Don't know if I am calling the function improperly or if I have the struct correct.
The program will compile and run up until it gets to the calling function for the quicksort. Then it just freezes and does nothing. Any help would be great. Thank you a head of time.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link_list;
};
struct node *insertion(struct node *pointer, int i){
struct node *temp_val;
if(pointer == NULL){
pointer = (struct node *)malloc(sizeof(struct node));
if(pointer == NULL){
printf("Error Exiting\n");
exit(0);
}
pointer->data = i;
pointer->link_list = pointer;
}else{
temp_val = pointer;
while(temp_val->link_list != pointer){
temp_val = temp_val->link_list;
}
temp_val->link_list = (struct node *)malloc(sizeof(struct node));
if(temp_val->link_list == NULL){
printf("Error Exiting\n");
exit(0);
}
temp_val = temp_val->link_list;
temp_val->data = i;
temp_val->link_list = pointer;
}
return(pointer);
};
struct node *findPivot(struct node *head, struct node *term, struct node **newHead, struct node **newTerm){
struct node *pivot = term;
struct node *previous = NULL, *current = head, *tail = pivot;
//finding the pivot and dividing the list while also updating the head and term
// with newHead and newTerm
while(current != pivot){
if(current->data < pivot->data){
//assigning the newHead to the first value less then the pivot
if((*newHead) == NULL){
(*newHead) = current;
}
previous = current;
current = current->link_list;
}else{
// if the current node has a higher value then the pivot
// assinging it to newTerm
if(previous){
previous->link_list = current->link_list;
}
struct node *temp = current->link_list;
current->link_list = NULL;
tail->link_list = current;
tail = current;
current = temp;
}
}
//Checks the case if the pivot is the smallest value and moves to head
if((*newHead)== NULL){
(*newHead) = pivot;
}
(*newTerm) = tail; // makes sure the last element is newEnd
return pivot;
}
//finds the last node in the list and returns it
struct node *getTail(struct node *current){
while(current != NULL && current->link_list != NULL){
current = current->link_list;
}
return current;
}
// the actual recursive quicksort algorithm
struct node *quickSort(struct node *head, struct node *term){
if(!head || head == term) //base case for the recursion
return head;
struct node *newHead = NULL, *newTerm = NULL;
// the recursive case
struct node *pivot = findPivot(head, term, &newHead, &newTerm);
//no need for recursion if pivot is smallest value
if(newHead != pivot){
struct node *temp = newHead;
while(temp->link_list != pivot){
temp = temp->link_list;
}
temp->link_list = NULL;
newHead = quickSort(newHead, temp);
temp = getTail(newHead);
temp->link_list = pivot;
}
pivot->link_list = quickSort(pivot->link_list, newTerm);
return newHead;
}
void quickSortFunction(struct node **pointer){
*pointer = quickSort(*pointer, getTail(*pointer));
return;
}
void printList_Unsorted(struct node *pointer){
struct node *temp;
temp = pointer;
printf("\nThe Data values in the list are:\n");
if(pointer != NULL){
do{
printf("%d\t", temp->data);
temp = temp->link_list;
}while(temp != pointer);
}else{
printf("the list is empty\n");
}
}
void printList_Sorted(struct node *node){
while(node!= NULL){
printf("%d ", node->data);
node = node->link_list;
}
printf("\n");
}
int main(int argc, char *argv[]) {
int num_nodes, node_val;
struct node *list = NULL;
printf("Enter the number of nodes to be created: ");
scanf("%d", &num_nodes);
while(num_nodes --> 0){
printf("\n\nEnter the data values to be placed in a node: ");
scanf("%d", &node_val);
list = insertion(list, node_val);
}
printf("\n\nThe Created list is as follow:\n");
printList_Unsorted(list);
printf("\n");
quickSortFunction(&list);
printList_Sorted(list);
//getchar();
//getchar();
return 0;
}
Please look at this working example.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link_list;
};
void insertion(struct node **pointer, int i) {
struct node *temp_val = malloc(sizeof *temp_val);
temp_val->data = i;
temp_val->link_list = (*pointer);
(*pointer) = temp_val;
}
/* A utility function to print linked list */
void printList(struct node *node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->link_list;
}
printf("\n");
}
// Returns the last node of the list
struct node *getTail(struct node *current) {
while (current != NULL && current->link_list != NULL)
current = current->link_list;
return current;
}
struct node *findPivot(struct node *head, struct node *term,
struct node **newHead, struct node **newTerm) {
struct node *pivot = term;
struct node *previous = NULL, *current = head, *tail = pivot;
while (current != pivot) {
if (current->data < pivot->data) {
if ((*newHead) == NULL)
(*newHead) = current;
previous = current;
current = current->link_list;
}
else
{
if (previous)
previous->link_list = current->link_list;
struct node *tmp = current->link_list;
current->link_list = NULL;
tail->link_list = current;
tail = current;
current = tmp;
}
}
// If the pivot data is the smallest element in the current list,
// pivot becomes the head
if ((*newHead) == NULL)
(*newHead) = pivot;
// Update newTerm to the current last node
(*newTerm) = tail;
// Return the pivot node
return pivot;
}
// the actual recursive quicksort algorithe
struct node *quickSort(struct node *head, struct node *end) {
// base case
if (!head || head == end)
return head;
struct node *newHead = NULL, *newEnd = NULL;
struct node *pivot = findPivot(head, end, &newHead, &newEnd);
if (newHead != pivot) {
struct node *tmp = newHead;
while (tmp->link_list != pivot)
tmp = tmp->link_list;
tmp->link_list = NULL;
newHead = quickSort(newHead, tmp);
tmp = getTail(newHead);
tmp->link_list = pivot;
}
pivot->link_list = quickSort(pivot->link_list, newEnd);
return newHead;
}
void quickSortFunction(struct node **headRef) {
(*headRef) = quickSort(*headRef, getTail(*headRef));
return;
}
int main() {
struct node *list = NULL;
int num_nodes, node_val;
printf("Enter the number of nodes to be created: ");
scanf("%d", &num_nodes);
while(num_nodes --> 0){
printf("\n\nEnter the data values to be placed in a node: ");
scanf("%d", &node_val);
insertion(&list, node_val);
}
printf("\n\nThe Created list is as follows:\n");
printList(list);
printf("\n");
quickSortFunction(&list);
printList(list);
return 0;
}
Test
/home/dac/.CLion2016.2/system/cmake/generated/gnu-fadf49ce/fadf49ce/Debug/gnu
Enter the number of nodes to be created: 3
Enter the data values to be placed in a node: 2
Enter the data values to be placed in a node: 4
Enter the data values to be placed in a node: 3
The Created list is as follows:
3 4 2
2 3 4
Process finished with exit code 0
The problem with your code was that it entered an infinite loop because the parameter was not a pointer to the node, but a pointer to the struct. You also don't need to return the list because you are passing it by reference.

appending node to link list (I am almost there) in C

I am trying to figure out how to append a node to the link list.
I feel like I am almost there but after staring at the code for a while now I cant think of whats wrong with it.
I have to mention that after adding first int to the list I get segmentation fault...
typedef struct node
{
int data;
struct node* next;
}
node;
node* head;
void append(node* pHead, int data)
{
node* current = pHead;
node* newNode = NULL;
newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
if (current == NULL)
pHead = newNode;
else
{
while (current->next != NULL)
current = current->next;
}
current->next = newNode;
}
int main(void)
{
head = NULL;
int howMany;
int num;
printf("how many?");
scanf("%d", &howMany);
for (int i = 0; i < howMany; i++)
{
printf("** %d ** number: ", i+1);
scanf("%d", &num);
append(head, num);
}
Where is my error?
I think the problem is here:
if (current == NULL)
pHead = newNode;
else
{
while (current->next != NULL)
current = current->next;
}
current->next = newNode;
That last line, current->next = newNode, should be inside the else body, otherwise you will try to dereference a NULL pointer when current is NULL.
So, it should be:
if (current == NULL)
pHead = newNode;
else
{
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
Another problem is that you never modify head. You only modify the private, local copy of the head pointer inside append(). This modification is not visible outside of append(), so the program ends up leaking memory and you can never access the list (because head is always NULL). You can either make pHead a node ** (so that modifications to *pHead are visible), or instead you can modify head inside append(), instead of passing it as an argument. This will work because you won't be modifying a private local copy. Here's how append() should look like:
void append(int data)
{
node* current = head;
node* newNode = NULL;
newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
if (current == NULL)
head = newNode;
else
{
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
}
You do current->next = newNode; even if current is NULL.
You must return from function when (current == NULL):
if (current == NULL) {
pHead = newNode;
return;
}
else
{
while (current->next != NULL)
current = current->next;
}
current->next = newNode;
or put current->next = newNode; in else statement:
if (current == NULL) {
pHead = newNode;
}
else
{
while (current->next != NULL)
current = current->next;
current->next = newNode;
}
Full example:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* next;
}
node;
node* head;
void append(node* pHead, int data)
{
node* current = pHead;
node* newNode = NULL;
newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
if (current == NULL) {
pHead = newNode;
return;
}
else
{
while (current->next != NULL)
current = current->next;
}
current->next = newNode;
}
int main(void)
{
head = NULL;
int howMany;
int num;
printf("how many?");
scanf("%d", &howMany);
for (int i = 0; i < howMany; i++)
{
printf("** %d ** number: ", i + 1);
scanf("%d", &num);
append(head, num);
}
}

Resources