I am trying to create a linked list with various options and, unfortunately, stuck at the process of inserting elements(hour and minute) at the beginning of a linked list.
My code is:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef struct node{
int hour, minute;
struct node* next;
}node;
void insert_beginning (node** root1, node** root2, int value) {
node* new_node = malloc(sizeof(node));
if (new_node == NULL) {
exit(1);
}
new_node->hour = value;
new_node->next = *root1;
new_node->minute = value;
new_node->next = *root2;
*root1 = new_node;
*root2 = new_node;
}
int main (int argc, char* argv[]) {
int option = 0;
node* root = NULL;
printf("Choose option: \n");
printf("1. Add time to the list. \n");
printf("2. Delete time from the list. \n");
printf("3. Change the postion of the bisst and the smallest elements. \n");
printf("4. Write the list. \n");
printf("5. Delete the list. \n");
printf("Your option: ");
scanf("%i", &option);
if (option == '1')
{
node* root1 = NULL;
node* root2 = NULL;
insert_beginning(&root1, &root2, 12, 15);
insert_beginning(&root1, &root2, 13, 20);
insert_beginning(&root1, &root2, 14, 25);
for (node* curr = root; curr != NULL; curr = curr->next)
{
printf("%d:%d\n", curr->hour, curr->minute);
}
}
return 0;
}
My problem is in these lines (I think):
insert_beginning(&root1, &root2, 12, 15);
insert_beginning(&root1, &root2, 13, 20);
insert_beginning(&root1, &root2, 14, 25);
**too many arguments to function call, expected 3, have 4**
But also I am afraid it does not compile from the beginning. (An example):
Choose option:
1. Add time to the list.
2. Delete time from the list.
3. Change the postion of the bisst and the smallest elements.
4. Write the list.
5. Delete the list.
Your option: 1
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
The goal is to receive a linked list like this (example):
Choose option:
1. Add time to the list.
2. Delete time from the list.
3. Change the postion of the bisst and the smallest elements.
4. Write the list.
5. Delete the list.
Your option: 1
14:25
13:20
12:15
I would highly appreciate your help!
Your program doesn't compile as insert_beginning() takes two node ** and a value but you call it with 4 arguments as noted by your compiler. You probably want 3 arguments node **, int hour and int minute.
You read int option but compare it against the character value ('1').
You have 3 root variables main(). You probably only want one.
In you first call *root1 and *root2 are NULL which will cause a segfault when you dereference those.
Always check the return value of scanf() otherwise you may be operating on uninitialized values. In your code you actually initialize option = 0 but your prompts suggest that you don't handle that case.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef struct node{
int hour;
int minute;
struct node* next;
} node;
void insert_beginning (node** root, int hour, int minute) {
node* new_node = malloc(sizeof(node));
if (!new_node) {
exit(1);
}
new_node->hour = hour;
new_node->minute = minute;
if(!*root) {
*root = new_node;
(*root)->next = NULL;
return;
}
new_node->next = *root;
*root = new_node;
}
int main (int argc, char* argv[]) {
node* root = NULL;
printf("Choose option: \n");
printf("1. Add time to the list. \n");
printf("2. Delete time from the list. \n");
printf("3. Change the postion of the bisst and the smallest elements. \n");
printf("4. Write the list. \n");
printf("5. Delete the list. \n");
printf("Your option: ");
int option;
if(scanf("%i", &option) != 1) {
printf("scanf failed\n");
exit(1);
}
if (option == 1) {
insert_beginning(&root, 12, 15);
insert_beginning(&root, 13, 20);
insert_beginning(&root, 14, 25);
for (node* curr = root; curr; curr = curr->next) {
printf("%d:%d\n", curr->hour, curr->minute);
}
}
}
and example output (note last in first out order as implies by "insert_beginning"):
Choose option:
1. Add time to the list.
2. Delete time from the list.
3. Change the postion of the bisst and the smallest elements.
4. Write the list.
5. Delete the list.
Your option: 1
14:25
13:20
12:15
Related
This is my algorithm for adding nodes to a linked list which is in a sorted way for surnames of persons.
Here is the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Node {
char Name[1024];
char Surname[1024];
char Telno[1024];
struct Node* next;
};
void Add(struct Node** firstnode, struct Node* NewNode)
{
struct Node* tempo;
//printf("%d",strcmp((*firstnode)->Surname,NewNode->Surname));
if (*firstnode == NULL || (strcmp((*firstnode)->Surname,NewNode->Surname) > 0)) {
NewNode->next = *firstnode;
*firstnode = NewNode;
}
else {
tempo = *firstnode;
while (tempo->next != NULL && strcmp(tempo->Surname,NewNode->Surname) < 0) {
tempo = tempo->next;
}
NewNode->next = tempo->next;
tempo->next = NewNode;
}
}
struct Node* CreateNode(char name[1024], char surname[1024], char telno[1024])
{
struct Node* NewNode = (struct Node*)malloc(sizeof(struct Node));
strcpy(NewNode->Name,name);
strcpy(NewNode->Surname,surname);
strcpy(NewNode->Telno,telno);
NewNode->next = NULL;
return NewNode;
}
void Printlinkedlist(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL) {
printf("%s %s %s\n", temp->Name,temp->Surname,temp->Telno);
temp = temp->next;
}
}
struct Node* head = NULL;
struct Node* temp;
int main()
{
int personcount;
char name[1024],surname[1024],telno[1024];
printf("Please give the count of person:");
scanf("%d", &personcount);
for (int i = 0; i < personcount; i++) {
printf("Please give the name of %d. person:", i + 1);
scanf(" %s", &name);
printf("Please give the surname of %d. person:", i + 1);
scanf(" %s", &surname);
printf("Please give the phone number of %d. person:", i + 1);
scanf(" %s", &telno);
temp = CreateNode(name,surname,telno);
Add(&head, temp);
}
printf("\n -------------- Linkedlist --------------\n");
Printlinkedlist(head);
return 0;
}
The first problem is this: For example, if I enter people's surnames as G, A, L, E, K (So first person's last name will be "G", second person's last name will be "A" etc..), it gives an incorrectly ordered output.
And the second one is: If I delete the comment line characters behind the printf inside the add function, I get a segmentation fault that I don't understand why
Thanks for the answer.
It should first be said that you could, and should, have figured it out yourself by either:
Debugging the program:
On Linux: How Can I debug a C program on Linux?
On Windows: How do you debug a C program on Windows?
Enabling core dumps and analyzing the core file you get when your program crashes; see this explanation.
But, more to the point, let's have a look at (some of) your code:
if (*firstnode == NULL || /* another condition */) {
// do stuff
}
else {
// so *firstnode may be NULL here
tempo = *firstnode;
while (tempo->next != /* some value */ && /* another condition*/ ) {
// do stuff
}
// do stuff
}
See the problem? tempo could get assigned a NULL point, and then de-referenced to get to the next field. That would likely cause a segmentation fault.
I want to programm a linked list in C, trying to apply everything I've learned so far.
I wrote this program to create a linked list:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node *head = NULL;
//Define struct node
struct node{
char * name;
int num;
struct node * next;
};
//Print List
void printList(){
struct node * temp = head;
while (temp != NULL){
printf("%s", temp->name);
printf("%d", temp->num);
temp = temp->next;
}
}
//Create New Node
struct node * newNode (char * name, int num){
struct node * newNode = (struct node*)malloc(sizeof(struct node));
newNode->name = name;
newNode->num = num;
newNode->next = NULL;
return newNode;
}
//Function to insert and sort Elements
void insertSorted (char * name, int num){
//Empty Liste -> Head is NULL
if (head == NULL){
head = newNode(name, num);
}
else if (strcmp(name, head->name) <=0){
// strcmp-output = -1 ->string 1 > string 2; 0 -> both strings are the same
struct node * temp = newNode(name, num);
temp->next = head;
head = temp;}
struct node * current = head; struct node *prev = NULL;
if (strcmp(name, current->name)>0){ //-> 1, string1 < string 2 ->insert after
while(current != NULL && strcmp(name, current->name)<=0){
prev = current;
current = current->next;
}
struct node * temp = newNode(name, num);
prev->next = temp;
temp->next = current;
}
}
//Test of the linked list
int main()
{
char name; int num;
//Testprogram
printf("Enter a name\n");
scanf("%s", &name);
printf("Enter a number\n");
scanf("%d", &num);
insertSorted(&name, num);
char name2; int num2;
printf("Enter a name\n");
scanf("%s", &name);
printf("Enter a number\n");
scanf("%d", &num2);
insertSorted(&name2, num2);*/
char name3; int num3;
printf("Enter a name\n");
scanf("%s", &name);
printf("Enter a number\n");
scanf("%d", &num3);
insertSorted(&name3, num3);
printList();
return 0;
}
Output example:
Input: Anna 1, Claudio 2, Berta 3
Output: 32Berta1
It somehow...makes the Names vanish and the numbers are in the wrong order too. I'm pretty new to programming, so I have troubles fixing this by myself.
Any help would be hugely appreciated :) Not only to fix the error, but also tips on how to program more...elegantly, so to say.
Thanks :)
//Edit:
Thank you for all the input so far! I messed up the input of the string while testing the program.
As suggested I tried to skip the part with the input, testing the linked list like this in main() (thanks Julien!):
insertSorted("Anna", 1);
insertSorted("Claudio", 2);
insertSorted("Berta", 3);
printList();
it results in the programm not executing and exiting with a negative number error code. Does this point to an infinite loop?
I haven't looked at the linked list details, but one issue I see is that you are using single char variable to store the names (which should be an array or characters). This lack of enough space to store the input make you program have an undefined behaviour after the call to scanf.
As #franji1 stated, try working step by step. If you want to check the code of your list, try testing:
insertSorted("Anna", 1);
insertSorted("Claudio", 2);
insertSorted("Berta", 3);
And check the result is what you expect. Once this is working, add the code asking for input from the user using scanf.
Im not an expert at C but since you mentioned code elegancy I can tell you this. You didn't need to use all these different if statements, you could use the while loop from the begining and insert after you find a name that is bigger than current. This will work even if it has to be inserted before the head node as long as you check that prev is not null. I hope I helped you and that you will find a solution to your problem!
I am trying to print out the results of the linked list in the reverse order that they were entered in. The program takes 3 inputs, Song name, song length (in seconds) and copyright. The program should take the list of songs and print the in the reverse order that they were entered in.
I am not too familiar with linked list. This is my first time using it as sort of a database.
#include <stdio.h>
#include <stdlib.h>
#pragma warning(disable:4996)
//defining struct
typedef struct node
{
char songName[20];
int songLength;
int copyright;
struct node * next;
}node;
//defining prototypes
node *create(int n);
void display(node *head);
int main()
{
int n = 0;
node *head = NULL;
printf("How many entries?\n");
scanf("%d", &n);
//call to create list
head = create(n);
printf("\nThe linked list in order is:\n");
display(head);
return 0;
}
node *create(int n)
{
node *head = NULL;
node *temp = NULL;
node *p = NULL;
for (int i = 0; i < n; i++)
{
temp = (node*)malloc(sizeof(node));
printf("What is the name of song %d\n", i + 1);
//fgets(temp->songName, 20, stdin);
scanf("%s", &temp->songName);
printf("What is the length of song %d (in seconds)?\n", i + 1);
scanf("%d", &temp->songLength);
printf("Is song %d copyrighted?(1 = YES, 0 = NO)\n", i + 1);
scanf("%d", &temp->copyright);
temp->next = NULL;
if (head == NULL)
{
head = temp;
}
else
{
// if not empty, attach new node at the end
p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
}
return head;
}
void display(node *head)
{
node *p = NULL;
if (head == NULL)
{
printf("List is empty\n");
}
else
{
p = head;
while (p != NULL)
{
printf("Song: %s, ", p->songName);
printf("%d minutes, ", p->songLength);
if (p->copyright == 1)
{
printf("Copyrighted\n");
}
else if (p->copyright == 0)
{
printf("No copyright\n");
}
p = p->next;
}
}
}
So if Input the following:
Song 1 - All Star (song name), 237 (seconds), 0 (no copyrights)
song 2 - Crab Rave, 193, 0
song 3 - 7 rings, 185, 1(copyrights)
The output should be:
7 rings, 185, 1
Crab Rave, 193, 0
All Star, 237, 0
If you have a single (forward) linked list, the probably easiest way to print it in reverse order is using recursion:
void display_recursive(node *n) {
if (!n) {
return;
}
display_recursive(n->next);
printf("Song: %s, ", n->songName);
...
}
Recursion means that a function is calling itself (until some end-condition, the anchor, is reached).
By that way, program flow will build up a "stack" of display_recursive- function calls, with the first node, then the second node, ..., until it reaches the last node; by then, recursion stops, and the print part of display_recursive is handled, starting with the last node backwards.
Hope this explanation helps; Try it out in the debugger to see what happens.
I have made a simple list like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
struct node{
int am;
struct node *next;
};
typedef struct node node;
int main(){
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->next=null;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
system("pause");
return 0;
}
Now travel is supposed to go through each node in the list and display the integer saved in each node.
void travel(node *h){
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Now the problem is that when travel is called it wont print the integer from the first node.It will also print another "Received data from node:" followed by a strange number.
For example
If i give 1,2,3,4 as inputs these are the results
Received data from node: 2
Received data from node: 3
Received data from node: 4
Received data from node: 4026432
Any ideas?
Now the problem is that when travel is called it wont print the
integer from the first node
This can be precisely known from this part of the main() function
printf("Give me a number:\n");
scanf(" %d",head->am); //this is wrong use of scanf("%d",&head->am);
cur=head;
while(1){
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->am=n;
as I've mentioned you're scanning wrongly but that doesn't matter because later in the code in while loop you replace it this way...
you scan number and store it at head->am
then you assign head to cur so head->am and cur->am are both the same now... so in while loop when you first assign n to cur->am, it gets assigned to head->am. so this explains why you never get to print first node.
Solution:
to overcome it ... in while loop, before assigning cur->am=n try doing:
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
//then... assign
curr->am=n;
this way you'll not lose first node.
suggestion:
As someone has already said it's much easier to traverse/ travel the list using loops (never mind... if you want to do it recursively)
here's how you do it with the loops:
void travel(node *h)
{
if(h==NULL)
return; //list is empty,consider printing "list empty" :)
while(h!=NULL)
{
printf("Received data from node: \t %d\n",h->am);
h=h->next;
}
}
To put all together your code without changing the travel() function as suggested would be:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int am;
struct node *next;
};
typedef struct node node;
void travel(node *h);
int main() //I have a habit of returning values from main() :)
{
int n;
node *head=(node *)malloc(sizeof(node));
node *cur=head;
printf("Give me a number:\n");
scanf(" %d",&head->am);
cur=head;
while(1)
{
printf("Give me a number\n");
scanf(" %d",&n);
if(n==0)
break;
cur->next=(node *)malloc(sizeof(node));
cur=cur->next;
cur->am=n; //NOTE:here's the change!
cur->next=NULL;
}
travel(head);
return 0; //just to signify successful compilation
}
void travel(node *h)
{
if(h==NULL)
return;
printf("Received data from node: \t %d\n",h->am);
travel(h->next);
}
Sample Input : 5 6 3 1 0
Sample Output :
Give me a number:
5
Give me a number
6
Give me a number
3
Give me a number
1
Give me a number
0
Received data from node: 5
Received data from node: 6
Received data from node: 3
Received data from node: 1
There are (at least) those issues:
The line scanf(" %d",head->am) is wrong since scanf() expects an address of the memory location of the expected value meaning &head->am.
Your loop scans a number and puts it in the current node and only after it creates a new node. Therefore, the first number you enter will be overridden (after fixing the first issue) and the last node created will contain random data because the loop will terminate after entering 0 but before putting anything in the last node.
I propose like this:
int main(void){
int n;
node anchor = {0, NULL};//dummy head
node *head, *cur = &anchor;
while(1){
printf("Give me a number\n");
scanf("%d", &n);
if(n==0)
break;
cur->next = malloc(sizeof(node));
cur = cur->next;
cur->am = n;
cur->next = NULL;
}
head = anchor.next;
travel(head);
printf("Total nodes available :%d\n", count(head));
return 0;
}
You are missing & at the first scanf:
scanf(" %d", &head->am);
But it could be made to do all the scanf inside the while:
int main(){
node *head=0;
node *cur=0;
node *prev=0;
while(1){
prev = cur;
cur=(node *)malloc(sizeof(node));
cur->next=NULL;
printf("Give me a number\n");
scanf("%d",&cur->am);
if(cur->am==0)
break;
if(head == NULL) head = cur;
if(prev != NULL) prev->next = cur;
}
travel(head);
printf("Total nodes available :%d\n",count(head));
return 0;
}
I hope I didnt make any mistake as I wrote it in this SO editor..
and as someone said, you should free the linked list .. but thats out of scope here..
HTH
I've been smashing my head here to see if I could find a solution but after few infinite loops, here's the code I'd like to be reviewed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TREE_STRING 100
typedef struct Node {
char val;
struct Node *next;
} node;
node *create_list(char *list_string) {
node *momentary=NULL, *new=NULL, *head;
int i;
for(i=0; i<strlen(list_string); i++) {
new = (node *)malloc(sizeof(node));
new->val = list_string[i];
new->next = NULL;
if (!momentary) head = new;
else momentary->next = new;
momentary = new;
}
return head;
}
int print_list(node *head) {
node *momentary;
if(!head) return -1;
for(momentary=head; momentary!=NULL; momentary=momentary->next)
printf("%c ", momentary->val);
printf("\n");
return 0;
}
node *find_biggest(node *head) {
node *momentary=NULL, *biggest=head;
if (head==NULL) return NULL;
for (momentary=head; momentary!=NULL; momentary=momentary->next) {
if (momentary->val > biggest->val) biggest = momentary;
}
return biggest;
}
void insert_after_biggest(node **head, node **biggest, char val) {
node *p = *head, *temp=NULL;
*head = p->next;
if(*head!=NULL){
if(p->val==(*biggest)->val){
temp=p;
p->next=temp;
p->val=temp->val;
p->next=NULL;
*biggest=p;
p->next=(*biggest);
p->val=(*biggest)->val;
//*biggest=p;
p->next=NULL;
//temp=p;
p->next=temp;
p->val=temp->val;
}
else if(p->val<(*biggest)->val){
*head = p->next;
}
}
}
int main () {
node *head=NULL, *biggest=NULL;
int menu_choice;
char c, val, list_string[MAX_TREE_STRING];
setbuf(stdout, NULL);
do {
menu_choice = 0;
printf("\n1 Create list \n2 Print");
printf("\n3 Insert after biggest");
printf("\n4 exit\n");
scanf("%d", &menu_choice);
switch (menu_choice) {
case 1:
if (head) {
printf("List exist.\n");
break;
}
printf("Enter list as digits without spaces: ");
scanf(" %s", list_string);
head = create_list(list_string);
break;
case 2:
print_list(head);
break;
case 3:
scanf(" %c", &val);
insert_after_biggest(&head, &biggest, val);
break;
case 4:
break;
default:
while((c=getchar())!='\n' && c!=EOF);
}
} while(menu_choice!=4);
return 0;
}
Now the task here is:
Write a function "insert_after_biggest" so that the new elements are
put behind the element with the highest value and complexity of the
function must be O (1). In other words, the function "find_biggest"
that has complexity of O (n) can be called only if the "biggest" has
not yet been defined. If the list has no elements , it still needs to
be first.
Here's a console example to have clearer picture:
1|<-Insert into linked list option|
Enter list as digits without spaces: 683 |<-Prompt and entered value|
3 |<-Option(the function)|
2 |<-Number to be inserted|
2 |<-Print option|
6 8 2 3|<-Output|
3 |<-Option|
8 |<-Number to be inserted|
2 |<-Print option|
8 |<-Output|
I've been typing this code myself and I have no idea anymore how to look at this.
I would humbly ask if someone can help me to solve this, the code compiles but executing the option 3 in the console only makes it run in infinite loop, resulting in crashing the console.
The specific: how to solve it (step by step) and how it should look like(the done code, possibly included here?).
Thank you.
If you can assume that
1) You don't need to remove elements
You merely need to keep an extra pointer that points to the node with the largest value at all times. It's nice that you are allowed to scan the list for the largest if you've never called
insert_after_biggest, but that's not even necessary. Call that node max, and the pointer to max p_max.
For each insertion
a) The value you're about to insert is larger than the value held by max, in which case you insert the new value, and change p_max = p_new.
n_new->next = p_max;
p_max = p_new;
b) The value you're about to insert is larger than the value held buy max, in which case simply insert and leave p_max unchanged.
For insert_after_max
you explicitly do
p_new->next = p_max->next;
p_max->next = p_new;
Or if the new value is larger then do as described above.
Since you don't have to scan the list to insert, the complexity of insertion is O(1)