Linked list insertion behaviour - c

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.

Related

Polynominal with doubly linked list - pointer problem

I made some polynomial code with a doubly-linked list. for example, if
you write 1 and 2 then 1 is a degree and 2 is coefficient. 1x^2 insert
to doubly linked list. the problem is that when I check my code, the Node
head->degree is changing. if I write 1x^2 then head->degree is 1 next,
I write 2x^1 then head-> degree should maintain 1 but head-> degree
change to 2 I think there is some problem in the head pointer.
#include <stdio.h>
#include <stdlib.h>
// struct
struct Node {
int degree;
int coefficient;
struct Node* next;
struct Node* prev;
};
// global variables
int de; // degree
int co; // coefficient
int flag;
Node** head = (Node**)malloc(sizeof(Node)); //
Node** head1 = (Node**)malloc(sizeof(Node)); //
Node** head2 = (Node**)malloc(sizeof(Node)); //
Node** head3 = (Node**)malloc(sizeof(Node)); //
Node* newNode = (Node*)malloc(sizeof(Node)); //
// function
Node* inputpoly(void);
void printNode(Node* inp);
Node* multiply(Node* a, Node* b);
// main
int main() {
// head null
(*head1) = NULL;
(*head2) = NULL;
(*head3) = NULL;
while (1) {
printf("Input (degree) (coefficient) : ");
scanf_s("%d %d", &de, &co);
if (de * co < 0) { continue; }
if (de < 0 && co < 0) {
printf("Done!\n");
break;
}
*head = inputpoly();
}
printNode(*head);
//multiply(*head1, *head2);
free(head1);
free(head2);
free(head3);
free(newNode);
free(head);
}
Node* inputpoly(void) {
// create Node
newNode->degree = de;
newNode->coefficient = co;
newNode->next = NULL;
newNode->prev = NULL;
// case1
if (flag == 0) {
// list
if ((*head1) == NULL) {
*head1 = newNode;
}
// list x
else {
Node* horse = (*head1);
// front of head
// ------------------There is some problem
printf("%d\n", 1);
printf("--%d\n", newNode->degree);
printf("--%d\n", horse->degree);
if (horse->degree > newNode->degree) {
newNode->next = horse;
horse->prev = newNode;
*head1 = newNode;
}
// barward of head
else {
int num = 0;
while (horse->next != NULL) {
horse = horse->next;
if (horse->degree > newNode->degree) {
horse->prev->next = newNode;
newNode->next = horse;
newNode->prev = horse->prev;
horse->prev = newNode;
num = 1;
break;
}
}
// behind tail
if (num == 0) {
horse->next = newNode;
newNode->prev = horse;
}
}
}
return *head1;
}
}
void printNode(Node* inp) {
Node* horse = inp;
if (horse == NULL)
{
return;
}
while (horse != NULL) {
if (horse->prev == NULL) {
if (horse->degree == 1) {
printf("%d", horse->coefficient);
}
else {
printf("%d x^%d", horse->coefficient, horse->degree);
}
}
else {
if (horse->degree == 1) {
printf(" + %d", horse->coefficient);
}
else {
printf(" + %d x^%d", horse->coefficient, horse->degree);
}
}
}
printf("\n");
}
"i think there is some head pointer problem, and if I fixed it I can this problem. so I want to maintain this code as possible. I want some
advice or solution to my head pointer"
The code posted in your example does not compile:
Before you can fix a head pointer problem the code must compile. This list of errors is detailing 2 things:
first, functions cannot be called outside of a function, eg:
Node** head = (Node**)malloc(sizeof(Node)); //
Node** head1 = (Node**)malloc(sizeof(Node)); //
Node** head2 = (Node**)malloc(sizeof(Node)); //
Node** head3 = (Node**)malloc(sizeof(Node)); //
Node* newNode = (Node*)malloc(sizeof(Node)); //
should be called from within main(void){...} or some other function.
second, every occurrence of Node should be prepended with struct. eg:
struct Node** head = malloc(sizeof(struct Node *));
(have also removed the cast, and modified the size of what you are creating memory for, i.e. a pointer)
Rather then fix these and other problems, here is an example of a doubly linked list that can demonstrate the structure of a simple working program. You can adapt the following to match your needs:
struct Node {
int deg;
int coef;
struct Node* next; // Pointer to next node in DLL
struct Node* prev; // Pointer to previous node in DLL
};
void inputpoly(struct Node** head_ref, int deg, int coef)
{
//allocate node
struct Node *new_node = malloc(sizeof(*new_node));
//assign data
new_node->deg = deg;
new_node->coef = coef;
//set next as new head and prev to null
new_node->next = (*head_ref);
new_node->prev = NULL;
//change prev of head to new */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
//point head to the new node */
(*head_ref) = new_node;
}
void printList(struct Node* node)
{
struct Node* last;
printf("\nread forward\n");
while (node != NULL) {
printf(" %d,%d ", node->deg,node->coef);
last = node;
node = node->next;
}
printf("\nread reverse\n");
while (last != NULL) {
printf(" %d,%d ", last->deg,last->coef);
last = last->prev;
}
}
int main(void)
{
//start with empty list
struct Node* head = NULL;
//create and populate new nodes
inputpoly(&head, 7, 2);
inputpoly(&head, 1, 4);
inputpoly(&head, 4, 6);
//ouput list
printList(head);
getchar();
return 0;
}
Note that this code is offered as a basic demonstration of creating doubly linked list, and illustrate how to traverse both directions. Because it does not free allocated memory, it is not recommended that it be used for any production purpose without addressing that omission.

Linked List elements not getting displayed

This is my program in C which always inserts into a linked list at the end. But when I try to print the list elements, nothing is displayed. Here is the code :
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void insert(struct Node *, int);
int main(void)
{
struct Node *head = NULL, *current;
int n, i, x, data;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &data);
insert(head, data);
}
current = head;
while(current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
}
void insert(struct Node *head, int data)
{
struct Node *newnode, *current = head;
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = data;
newnode->next = NULL;
if(head == NULL)
{
head = newnode;
}
else
{
while(current->next != NULL)
{
current = current->next;
}
current->next = newnode;
}
}
I cannot understand what might be the issue. Please help.
Your insert cannot modify head. Change it to
void insert(struct Node **head, int data)
and change it by
*head = newnode;
and call it like this
insert(&head, data);
Here, while you are passing the head pointer to your insert() function, it is not being updated in your main() function.
So, either declare your head pointer as global or return your head pointer and update it in your main() function.
In the below code I had taken the head pointer as global and removed the head pointer as your parameter from the insert() function.
Here is the code :-
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head=NULL;
void insert(int);
int main(void)
{
struct Node *current;
int n, i, x, data;
clrscr();
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &data);
insert(data);
}
current = head;
while(current != NULL)
{
printf("%d \n", current->data);
current = current->next;
}
getch();
return 0;
}
void insert(int data)
{
struct Node *newnode, *current = head;
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = data;
newnode->next = NULL;
if(head == NULL)
{
head = newnode;
}
else
{
while(current->next != NULL)
{
current = current->next;
}
current->next = newnode;
}
}
You need to pass the reference of the head pointer, then only the changes made to it will be visible.
You must declare your function like
void insert(struct Node **, int);
and also call it like
insert(&head, data);
also, make changes to function definition
void insert(struct Node **head, int data)
{
struct Node *newnode, *current = *head;
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = data;
newnode->next = NULL;
if(*head == NULL)
{
*head = newnode;
}
else
{
while(current->next != NULL)
{
current = current->next;
}
current->next = newnode;
}
}
You need to pass the head by reference as you are making changes to it that should be visible.
insert(head, data);
should become
insert(&head, data);
Also the function signature will change.
void insert(struct Node *head, int data)
should become
void insert(struct Node **head, int data)
Also make appropriate changes in the function.
Like,
current = *head;
Because you are passing the pointer by value. The function operates on a copy of the pointer, and never modifies the original.
Either pass a pointer to the pointer (i.e. a struct head **), or instead have the function return the pointer.
You can try running the following code which will give the output as null
printf("%s",head);
while(current != NULL)
{
printf("%d", current->data);
current = current->next;
}

Linked List K Alternate Reverse Program

Can Anyone Explain me why the function *kAltReverse return node type prev and how it will work when you call node->next in print function to get the next element from the struct node & print and how it points to next data?
I don't understand how the data is printed using just prev in *kAltReverse function?
Help is very very highly appreciated!!!
Question Source: GeeksforGeeks
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* next; };
struct node *kAltReverse(struct node *head, int k) {
struct node* current = head;
struct node* next;
struct node* prev = NULL;
int count = 0;
while (current != NULL && count < k)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if(head != NULL)
head->next = current;
count = 0;
while(count < k-1 && current != NULL )
{
current = current->next;
count++;
}
if(current != NULL)
current->next = kAltReverse(current->next, k);
return prev;
}
void push(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 printList(struct node *node) {
int count = 0;
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
count++;
}
}
int main(void) {
struct node* head = NULL;
for(int i = 20; i > 0; i--)
push(&head, i);
printf("\n Given linked list \n");
printList(head);
head = kAltReverse(head, 3);
printf("\n Modified Linked list \n");
printList(head);
getchar();
return(0);
}
Looks like there is a problem with int count = 0;.
It should be static int count = 0;, otherwise it would not behave as expected.
This reverses 1st 'k' elements of the linked list using recursion. Its like in 1st iteration of the loop, the 1st element will be placed at Kth position and 2nd element at 1st position, and in next iteration, with k reduced by 1, it will placed the 2nd value(the current 1st value after iteration) to the (k-1)th position (last position for current iteration). This goes on till count reaches to 'k'.

Deleting front node from a Singly Linked List in 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

Pointers Linked Lists C Programming

I don't get why this isn't working... For example I have this.
struct node {
int data;
struct node* next;
};
static int length(struct node* head) {
Does Stuff
};
void main() (
int i;
struct node* head;
i = length(head);
);
but the code doesn't want to work... I get the wrong output. I'm trying to send the pointer to my functions so that they can have access to the data that I malloc. I will post the full code bellow:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
static int length(struct node* head);
static void push(struct node* head, int data);
static int pop(struct node* head);
static void appendNode(struct node* head, int data);
static struct node *copyList(struct node* head);
static void printList(struct node* head);
/************************************************************
length - return length of a list
************************************************************/
int length(struct node* head) {
int count = 0;
struct node* current = NULL;
current = head;
while (current != NULL) {
current = current->next;
++count;
}
return count;
}
/************************************************************
push - add new node at beginning of list
************************************************************/
void push(struct node* head, int data) {
struct node* new_ptr = NULL;
new_ptr = (struct node*)malloc(sizeof(struct node));
new_ptr->data = data;
new_ptr->next = head;
head = new_ptr;
}
/************************************************************
pop - delete node at beginning of non-empty list and return its data
************************************************************/
int pop(struct node* head) {
int val = 0;
struct node* temp = NULL;
if (head != NULL) {
val = head->data;
temp = head->next;
free(head);
head = temp;
}
return(val);
}
/************************************************************
appendNode - add new node at end of list
************************************************************/
void appendNode(struct node* head, int data) {
struct node* current = NULL;
struct node* previous = NULL;
struct node* new_ptr = NULL;
current = head;
previous = current;
while (current != NULL) {
previous = current;
current = current->next;
}
new_ptr = (struct node*)malloc(sizeof(struct node));
new_ptr->data = data;
new_ptr->next = NULL;
previous = new_ptr;
}
/************************************************************
copyList - return new copy of list
************************************************************/
struct node* copyList(struct node* head) {
struct node* copy = NULL;
struct node* current = NULL;
struct node* new_ptr = NULL;
/* Copy current head to copy */
current = head;
while (current != NULL) {
appendNode(copy, current->data);
current = current->next;
}
return copy;
}
/************************************************************
printList - print linked list as "List: < 2, 5, 6 >" (example)
************************************************************/
void printList(struct node* head) {
struct node* current = NULL;
printf("List: < ");
current = head;
if (current == NULL)
printf("none ");
while (current != NULL) {
printf("%d", current->data);
current = current->next;
if (current != NULL)
printf(", ");
}
printf(" >\n");
}
void main() {
int i; // index used for loops
struct node *list_a; // a new list
struct node *list_a_copy; // copy of list
list_a = NULL; // initialize empty list
list_a_copy = NULL; // initialize empy list
// test push
for (i = 0; i < 4; ++i)
push(list_a, i);
// test length
printf("Length of list = %d\n", length(list_a));
// test print head list
printf("head:\n");
printList(list_a);
// test append node
for (i = 4; i < 8; ++i)
appendNode(list_a, i);
// test print head list
printf("head(append):\n");
printList(list_a);
// make a copy of list
list_a_copy = copyList(list_a);
// test pop head list
for (i = 0; i < 4; ++i)
printf("%d popped\n", pop(list_a));
// test print copy list
printf("head copy:\n");
printList(list_a_copy);
// test pop copy list
for (i = 0; i < 4; ++i)
printf("%d popped\n", pop(list_a_copy));
}
Thank you for you help. I'm still learning these C pointers, and I know I'm close.
Cheers
I looked into function push():
void push(struct node* head, int data) {
struct node* new_ptr = NULL;
new_ptr = (struct node*)malloc(sizeof(struct node));
new_ptr->data = data;
new_ptr->next = head;
head = new_ptr;
}
The way you assign head = new_ptr; is wrong. Doing so only, head has effect within in the function, head won't be pointed to the memory you allocated after push() is called. So you need to fix your push() function:
void push(struct node **head, int data) {
if ((*head) == null)
(*head) = (struct node*)malloc(sizeof(struct node));
(*head)->data = data;
(*head)->next = head;
}
The problem is that you are passing a pointer to a node in your methods. This means that what you are modifying is a local parameter and not what you are passing to the method. Why is this? Because passing by value copies the parameter, to the address is directly copied.
struct Node *list_a = NULL;
push(list_a, 5);
When you call push, what happens is that a copy of the variable list_a is pushed onto the stack and then the function is called. The same thing, if you think about it, happens with simple cases:
int x = 5;
add(x, 5);
void add(int a, int b) { a += b; } // <-- this won't modify the x passed
So here
void push(struct Node *head, int value) {
head = something;
}
you are not modifying the original list_a but rather a copy of it which has been passed to the function.
To be able to modify the original pointer you need to pass the address to it, so a pointer to the pointer of the head of the list. This can be done easily:
struct Node *list_a = NULL;
push(&node, 5);
void push (struct Node **node, int value) {
...
*node = malloc(..);
}
So here the address of the variable list_a is passed to the function, dereferencing it allows you to modify the real value instead that just a copy.

Resources