I'm writing a program that adds a node at the end of an existing linked list.
The problem is that it doesn't seem to assign to the variable nr of struct node of the last element of the linked list the hard coded value 7.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
struct node {
int nr;
struct node *next;
};
void addNodes(struct node **head, int n);
void displayList(struct node *head);
void addItemLast(struct node *head);
int main() {
struct node* head = NULL;
int n;
printf("Introduceti numarul de noduri: ");
scanf("%d", &n);
addNodes(&head, n);
displayList(head);
addItemLast(head);
displayList(head);
return 0;
}
void addNodes(struct node **head, int n) {
*head = (struct node*)malloc(sizeof(struct node));
struct node *current = *head;
printf("\nIntroduceti %d noduri:\n", n);
for(int i = 0; i < n; i++) {
printf("Element %d = ", i+1);
scanf("%d", &(current -> nr));
current->next = (struct node*)malloc(sizeof(struct node));
current = current->next;
}
current->next = NULL;
}
void displayList(struct node *head) {
struct node *current = head;
int i = 1;
printf("\nElementele introduse sunt:\n");
while(current->next != NULL) {
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}
}
void addItemLast(struct node *head) {
struct node *temp = head, *last;
last = (struct node*)malloc(sizeof(struct node));
if(last == NULL) {
printf("\nMemory cannot be allocated!\n");
} else {
last->nr = 7;
last->next = NULL;
while(1) {
if(temp->next == NULL) {
temp->next = last;
break;
}
temp = temp->next;
}
}
}
The last function, addItemLast(), doesn't work as expected.
This is the output:
Introduceti numarul de noduri: 3
Introduceti 3 noduri:
Element 1 = 1
Element 2 = 2
Element 3 = 3
Elementele introduse sunt:
Elementul 1 = 1
Elementul 2 = 2
Elementul 3 = 3
After the function with the problem runs, I get this output:
Elementele introduse sunt:
Elementul 1 = 1
Elementul 2 = 2
Elementul 3 = 3
Elementul 4 = 13383248
Element 4 does not contain the hard coded value 7, but instead has a garbage value and I can't figure out why.
Your implemenation of addNodes is incorrect, suppose I enter n = 2 , 3 nodes are created but only twice scanf function is called, so as result you have garbage value in some node (nr is not set).
Reimplement it (it works if addItemLast function is properly implemented) :
void addNodes(struct node **head, int n){
printf("\nIntroduceti %d noduri:\n", n);
for(int i = 0; i < n; i++){
struct node* last = addItemLast(*head);
if (*head == NULL)
*head = last;
printf("Element %d = ", i);
scanf("%d", &(last -> nr));
}
}
You need to change addItemLast to handle case when you want to call this function but head is NULL (without testing this case your program crashes while calling addItemLast for empty List):
struct node* addItemLast(struct node *head){
struct node *temp = head, *last;
last = (struct node*)malloc(sizeof(struct node));
if (head == NULL) // <---------
{
last->nr = 7;
last->next = NULL;
return last;
}
if(last == NULL){
printf("\nMemory cannot be allocated!\n");
}else{
last->nr = 7;
last->next = NULL;
while(1){
if(temp->next == NULL){
temp->next = last;
break;
}
temp = temp->next;
}
}
return last;
}
and finally function to display list should be:
void displayList(struct node *head){
struct node *current = head;
int i = 1;
printf("\nElementele introduse sunt:\n");
while(current != NULL){ // <---------
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}
}
You do not have to check if current->next != NULL when accessing the element of current.
Change your while loop to:
while(current != NULL){
printf("Elementul %d = %d\n", i, current->nr);
current = current->next;
i++;
}
Related
im starting to learn data structures and i tried to making a simple program about a single linked list.
The problem is that when i call my display function (transversing the list) it doesn't give me an output? What is wrong with my code and how do i fix this?
This my program:
int main(){
int n;
printf(" Input the number of nodes : ");
scanf("%d", &n);
create(n);
printf("\n Data entered in the list : \n");
display();
}
void create(int n)
{
struct node *head=NULL;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for node 1 : ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
for(i=1; i<n; i++) // Creating n nodes
{
struct node *current = (struct node *)malloc(sizeof(struct node)); // addnode
if(current == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &data);
current->data = data;
current->next = NULL;
head->next = current;
head = head->next;
}
}
}
}
My Traversing function:
void display(struct node *head)
{
struct node* ptr = head;
if(head == NULL)
{
printf(" List is empty.");
}
else
{
while(ptr != NULL)
{
printf(" Data = %d\n", ptr->data);
ptr = ptr->next;
}
}
}
The problem are lines in create()
head->next = current;
head = head->next;
this operation set head to current. Note that current->next is NULL. As result the entire content of the list is lost except the last element.
Just replace those lines with:
current->next = head;
head = current;
This will put the current node at the top of the list.
Remember to return head from create().
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * create(int n) {
struct node *head=NULL;
int data, i;
struct node * ptmp = NULL;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL) {
printf(" Memory can not be allocated.");
} else {
printf(" Input data for node 1 : ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
ptmp = head;
for(i=1; i<n; i++) {
struct node *current = (struct node *)malloc(sizeof(struct node)); // addnode
if(current == NULL) {
printf(" Memory can not be allocated.");
break;
} else {
printf(" Input data for node %d : ", i);
scanf(" %d", &data);
#if 0
// insert first
current->data = data;
current->next = head;
head = current;
#else
// insrt last
current->data = data;
current->next = NULL;
ptmp->next=current;
ptmp = current;
#endif
}
}
}
return head;
}
void display(struct node *head)
{
struct node* ptr = head;
if(head == NULL) {
printf(" List is empty.");
} else {
while(ptr != NULL) {
printf(" Data = %d\n", ptr->data);
ptr = ptr->next;
}
}
}
int main() {
int n = 0;
printf(" Input the number of nodes : ");
scanf("%d", &n);
if (n<=0 || n > 6400) {
printf("Invalid input : %d (Enter value in range 0-6400)\n", n);
return 0;
}
struct node * head = create(n);
printf("\n Data entered in the list : \n");
display(head);
}
Hi this is the code I wrote for create as many nodes as he needs (the m variable), but I noticed that using this method I'm creating one more node. What's the best way of fcreating as many nodes as the user say us?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int val;
int rip;
struct Node *next;
} node;
node *modify(node *head);
void print(node *head2);
int main(){
int m, i;
printf("How many nodes: \n");
scanf("%d", &m);
node *head = NULL;
head = (node *)malloc(sizeof(node));
node *temp = head;
node *head2 = NULL;
printf("Write the value in HEAD position : \n");
scanf("%d", &temp->val);
temp->rip=0;
temp->next = NULL;
for(i=0; i < m-1; i++)
{
temp->next = (node *)malloc(sizeof(node));
printf("Write the value in position %d: \n", i);
temp = temp->next;
scanf("%d", &temp->val);
temp->rip=0;
temp->next = NULL;
}
head2 = modify(head);
print(head2);
return 0;
}
node *modify(node *head){
int counter, pass, m;
node *curr = head;
node *track = head;
node *precNode;
while (track != NULL){
counter = 0;
pass = 0;
m = track->val;
while( curr != NULL){
if(m == (curr)->val){
pass++;
counter++;
if(pass > 1){
node *removed = curr;
precNode->next = (curr)->next;
curr = (curr)->next;
free(removed);
}
if(pass == 1)
{
precNode = curr;
curr = curr->next;
}
}
else{
precNode = curr;
curr = (curr)->next;
}
}
track->rip = counter;
track = track->next;
curr = track;
}
return head;
}
void print(node *head2){
while(head2 != NULL){
printf("[%d, %d] -> ", head2->val, head2->rip);
head2 = head2->next;
}
printf("\n");
}
```
I coded a basic linked list working by pointers. It has functions for creating, inserting, deleting, and finding nodes according to positions.
For some reason, the build output says
1>Done building project "Linked List.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
There are no errors unfortunately, so I don't understand what's the problem.
Does anyone see what I'm missing here?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
struct node *head = NULL;
void PrintList()
{
struct node *temp = (node*)malloc(sizeof(node));
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
node* New(int data)
{
node *new = (node*)malloc(sizeof(node));
if (new == NULL)
{
printf("Error \n");
exit(0);
}
new->data = data;
new->next = NULL;
return new;
}
void Create(int data)
{
node *temp = head;
while (temp->next != NULL)
temp = temp->next;
node *new = New(data);
temp->next = new;
}
void Insert(int data, int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
temp1->data = data;
temp1->next = NULL;
if (position == 0)
{
temp1->next = head;
head = temp1;
return;
}
struct node *temp2 = (struct node*)malloc(sizeof(struct node*));
for (int i = 0; i < position - 2; i++)
{
temp2 = temp2->next;
temp2->next = temp1;
}
}
void Delete(int position)
{
struct node *temp1 = (struct node*)malloc(sizeof(struct node*));
if (position == 0)
{
head = temp1->next;
free(temp1);
return;
}
for (int i = 0; i < position - 2; i++)
temp1 = temp1->next;
struct node *temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
int Find(int position)
{
struct node *temp = (node*)malloc(sizeof(node));
for (int i = 0; i < position + 1; i++)
temp = temp->next;
return temp->data;
free(temp);
}
void menu()
{
printf("Linked List in C \n\n");
printf("1.Create an element\n");
printf("2.Insert as the kth element\n");
printf("3.Delete the kth element\n");
printf("4.Find the kth element\n");
printf("0.Exit\n");
}
int main()
{
int command;
int data;
int position;
head = NULL;
menu();
while (1)
{
printf("\nEnter a command (0~4):");
scanf("%d", &command);
if (command == 0)
break;
switch (command)
{
case 1:
printf("Enter a number to be created as the last element: \n");
scanf("%d", data);
Create(data);
PrintList();
break;
case 2:
printf("Enter a number to insert into the list: \n");
scanf("%d", data);
printf("Enter the position to insert this element: \n");
scanf("%d", position);
Insert(data, position);
PrintList();
break;
case 3:
printf("Enter the position of the element to be deleted: \n");
scanf("%d", position);
Delete(position);
PrintList();
break;
case 4:
printf("Enter the position of the element you are looking for: \n");
scanf("%d", position);
int X = Find(position);
printf("The element in node %d is %d. \n", position, X);
PrintList();
break;
}
}
//dispose(head);
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Lists seem really hard for me. I want to find the smallest element in a file: 1 5 8 6 4 8 6 48 9. It's 1 and I want to delete that 1. I can find the smallest element but can not delete it. I find the smallest element place but not the value. I tried copying deleting function from the web, however I cant understand it due to the fact that I'm really new to C. It writes an error that dereferencing to incomplete type. Please help. Post whole code because it should be more convenient to understand.
#include <stdio.h>
#include <stdlib.h>
typedef struct linkedList {
int value;
struct linkedList *next;
} linkedList, head;
linkedList *readList(linkedList *head) {
FILE *dataFile;
dataFile = fopen("duom.txt", "r");
if (dataFile == NULL) {
printf("Nepasisekė atidaryti failo\n");
} else {
printf("Duomenų failą pavyko atidaryti\n");
}
while (!feof (dataFile))
if (head == NULL) {
head = malloc(sizeof(linkedList));
fscanf(dataFile, "%d", &head->value);
head->next = NULL;
} else {
struct linkedList *current = head;
struct linkedList *temp = malloc(sizeof(linkedList));
while (current->next != NULL) {
current = current->next;
}
fscanf(dataFile, "%d", &temp->value);
current->next = temp;
temp->next = NULL;
}
return head;
}
void search(linkedList *head, int *lowest) {
int a[100];
int i = 0;
int minimum;
int b = 0;
linkedList *current = head;
while (current != NULL) {
a[i] = current->value;
current = current->next;
i++;
}
b = i;
i = 0;
minimum = a[0];
while (b > 0) {
if (minimum > a[i]) {
minimum = a[i];
lowest = i;
}
i++;
b--;
}
}
void deleteNode(struct node **head_ref, int key) {
struct node* temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
return;
prev->next = temp->next;
free(temp);
}
void printList(linkedList *head) {
linkedList *current = head;
while (current != NULL) {
printf("%d->", current->value);
current = current->next;
}
printf("NULL\n");
return;
}
int main() {
linkedList *A = NULL;
A = readList(A);
search(A);
head = head->next;
minimum = head->value;
headk->next = head->next;
free(head);
printList(A);
return 0;
}
like this
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct linkedList{
int value;
struct linkedList *next;
} linkedList, node;
linkedList *readList(void){
FILE *dataFile;
dataFile = fopen("duom.txt", "r");
if(dataFile == NULL) {
perror("file open");
return NULL;
}
int v;
node head = {0, NULL}, *curr = &head;
while (1 == fscanf(dataFile, "%d", &v)){
node *new_node = malloc(sizeof(node));
if(new_node == NULL){
perror("malloc");
break;
}
new_node->value = v;
new_node->next = NULL;
curr = curr->next = new_node;
}
fclose(dataFile);
return head.next;
}
int searchMin(linkedList *head){
if(head == NULL){
fprintf(stderr, "%s: The list MUST NOT be NULL.\n", __func__);
return INT_MIN;
}
int min = head->value;
node *p = head->next;
while(p){
if(p->value < min)
min = p->value;
p = p->next;
}
return min;
}
void deleteNode(node **head_ref, int key){
node *curr = *head_ref, *prev = NULL;
while (curr != NULL && curr->value != key){
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;//not found
if(prev)
prev->next = curr->next;
else
*head_ref = curr->next;
free(curr);
}
void printList(linkedList *head){
node *current = head;
while (current != NULL) {
printf("%d->", current->value);
current = current -> next;
}
puts("NULL");
}
void freeList(linkedList *list){
while(list){
node *temp = list;
list = list->next;
free(temp);
}
}
int main(void){
linkedList *A = readList();
int min = searchMin(A);
printList(A);
deleteNode(&A, min);
printList(A);
freeList(A);
return 0;
}
Please try if this program can help you.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct node {
int data;
struct node *next;
};
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 deleteNode(struct node **head_ref, int key) {
struct node *temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
void printList(struct node *node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
void min(struct node **q) {
struct node *r;
int min = INT_MAX;;
r = *q;
while (r != NULL) {
if (r->data < min) {
min = r->data;
}
r = r->next;
}
printf("The min is %d", min);
deleteNode(q, min);
printf("\n");
}
int main() {
struct node *head = NULL;
FILE *file = fopen("duom.txt", "r");
int i = 0;
fscanf(file, "%d", &i);
while (!feof(file)) {
push(&head, i);
fscanf(file, "%d", &i);
}
fclose(file);
puts("Created Linked List: ");
printList(head);
min(&head);
puts("\nLinked List after Deletion of minimum: ");
printList(head);
return 0;
}
file duom.txt
1 5 8 6 4 8 6 48 9
Test
./a.out
Created Linked List:
9 48 6 8 4 6 8 5 1 The min is 1
Linked List after Deletion of minimum:
9 48 6 8 4 6 8 5 ⏎
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.