Hi I'm creating a program for school where I have to:
Create structures
Create functions to print my linked list
Create functions to insert an ordered element
Delete elements with a minor year less than the year selected
I created all a part the last one step.
Can you help me to know what is the right way?
This is my code:
STRUCTURE:
typedef struct dimension {
int height;
int length;
} DIMENSION;
typedef struct pic {
DIMENSION d;
char name[50];
int year;
} PIC;
typedef struct node {
PIC p;
struct node *next;
} NODE;
PRINT LIST:
void printPic(PIC p) {
printf("Autor: %s\nDimension\nHeight: %d\nLength: %d\nYear: %d\n", p.name, p.d.height, p.d.length, p.year);
}
void printList(NODE *head) {
if(head->next==NULL) {
printf("No element in the list!\n");
} else {
while(head->next != NULL) {
head = head->next;
printPic(head->p);
}
}
}
NEW PIC(ORDERED WITH AREA DIMENSION)
int area(PIC p) {
return (p.d.height * p.d.length);
}
PIC createPic() {
PIC newPic;
printf("Author: ");
fgets(newPic.name, 50, stdin);
newPic.name[strlen(newPic.name)-1] = '\0';
printf("Height: ");
scanf("%d", &newPic.d.height);
printf("\n");
printf("Length: ");
scanf("%d", &newPic.d.length);
printf("\n");
printf("Year: ");
scanf("%d", &newPic.year);
printf("\n");
printf("\n");
return newPic;
}
void insertPic(NODE *head) {
NODE* newNode = malloc(sizeof(NODE));
newNode->p = createPic();
newNode->next = NULL;
if(head==NULL) {
head = newNode;
} else {
if(area(newNode->p) < area(head->p)) {
newNode->next = head;
head = newNode;
} else {
while(head->next != NULL && (area(newNode->p) > area(head->next->p))) {
head = head->next;
}
newNode->next = head->next;
head->next = newNode;
}
}
}
DELETE ELEMENTS WITH A MINOR YEAR THAN SELECTED YEAR:
Edited and now it works:
void deletePic(NODE *head, int year) {
if(head==NULL) {
printf("No element in the list!\n");
} else {
while(head->next != NULL) {
if(head->next->p.year < year) {
NODE *p = head->next;
head->next = p->next;
free(p);
} else {
head = head->next;
}
}
}
}
MAIN:
int main() {
NODE *head = malloc(sizeof(NODE));
head->next = NULL;
int choice = -1;
while(choice != 0) {
printf("Select an action:\n");
printf("Press 1 --> See list\n");
printf("Press 2 --> Insert a new element\n");
printf("Press 3 --> Delete elements with a minor year\n");
printf("Press 0 --> Stop program\n");
scanf("%d%*c", &choice);
if(choice==1) {
printList(head);
}
else if(choice==2) {
insertPic(head);
}
else if(choice==3) {
int year;
printf("Choose an year\nAll elements with a smaller year will be eliminated\n");
scanf("%d", &year);
deletePic(head, year);
}
else if(choice==0) {
printf("See you soon ;)\n");
}
}
}
Your deletePic function is broken in multiple places. Among them:
Dereferencing an indeterminate pointer, yearNode
Incorrect comparator (should use < ; not !=
free'ing an indeterminate pointer.
The first and last of those are a recipe for disaster. If that function does what the menu claims it should, I think what you want is this:
void deletePic(NODE *head, int year)
{
if (head == NULL)
{
printf("No element in the list!\n");
}
else
{
while (head->next != NULL)
{
if (head->next->p.year < year)
{
NODE *p = head->next;
head->next = p->next;
free(p);
}
else
{
head = head->next;
}
}
}
}
Related
I am trying to write a code to implement a linked list. The program inserts a value taken from the user into a linked list until the user exits execution. The value can be inserted into the head, tail or any custom position entered by the user.
Upon compiling the program gives the error "Return value ignored: 'scanf'" on every scanf. It also gave an error saying scanf is unsafe, use scanf_s instead. I resolved that by adding '_CRT_SECURE_NO_WARNINGS' to preprocessor definitions. Also please point out if you find any other mistakes.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} node;
typedef enum position { First = 1, Custom, Last} position;
typedef enum process {Exit, Run} process;
node* insertFirst(node* ptrHead, int val)
{
node* temp = NULL;
node* newNode = (node*)malloc(sizeof(node));
if (newNode == NULL)
{
exit(1);
}
else
{
if (ptrHead == NULL)
{
newNode->data = val;
newNode->next = NULL;
ptrHead = newNode;
}
else
{
temp = ptrHead;
newNode->data = val;
newNode->next = temp;
ptrHead = newNode;
}
}
return ptrHead;
}
node* insertPos(node* ptrHead, int val, int loc)
{
node* temp = ptrHead;
node* newNode = (node*)malloc(sizeof(node));
if (newNode == NULL)
{
exit(1);
}
for (int i = 0; i < loc; i++)
{
temp = temp->next;
}
newNode->data = val;
newNode->next = temp->next;
temp->next = newNode;
return ptrHead;
}
node* insertLast(node* ptrHead, int val)
{
node* temp = ptrHead;
node* newNode = (node*)malloc(sizeof(node));
if (newNode == NULL)
{
exit(1);
}
newNode->data = val;
newNode->next = NULL;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
return ptrHead;
}
void printList(node* ptrHead)
{
node* temp = ptrHead;
while (temp->next != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
}
int countNodes(node* ptrHead)
{
node* temp = ptrHead;
int i = 0;
while (temp->next != NULL)
{
temp = temp->next;
i++;
}
return i;
}
int main()
{
node* ptrHead = NULL;
position location;
int num = 0;
int pos = 0;
process state = Run;
while (state == Run)
{
printf(" Welcome to my Linked List program. \n");
if (ptrHead == NULL)
{
printf("Enter first element of the list \n");
scanf("%d", &num);
ptrHead = insertFirst(ptrHead, num);
}
else
{
printf(" Enter number to choose location: \n 1 -> First\n 2-> Custom\n 3-> Last\n");
scanf("%d", &pos);
if (pos == Custom)
{
printf("Please enter the number and the placement\n");
scanf("%d", &num);
scanf("%d", &location);
if (location > countNodes(ptrHead))
{
printf("Enter position less than %d\n", countNodes(ptrHead));
}
else
{
ptrHead = insertPos(ptrHead, num, location);
}
}
else if (pos == First)
{
printf("Please enter the number\n");
scanf("%d", &num);
ptrHead = insertFirst(ptrHead, num);
}
else if (pos == Last)
{
printf("Please enter the number\n");
scanf("%d", &num);
ptrHead = insertLast(ptrHead, num);
}
else
{
printf("Wrong position entry\n");
}
}
printList(ptrHead);
printf("Enter '1' to insert another value and '0' to quit execution\n");
scanf("%d", &state);
}
return 0;
}
recently i just learning about c and c++, and now i get assignment about creating simple music playlist in C using queue linked list, what i want ask why my song list not appear on the screen ?
is there something wrong with my code, pleas enlight me
i am sorry newbie on stackoverflow too, still not getting use to stackoverflow
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* front = NULL;
struct node* rear = NULL;
struct node* temp;
int songSlot;
char* song[50]= {
"IDGAF - Dua Lipa",
"FRIENDS - Marshmello, Anne-Marie",
"The Middle - Zedd, Maren Morris, Grey",
"Best Part - H.E.R., Daniel Caesar",
"All The Stars (with SZA) - Kendrick Lamar, LZA",
"Wolves - Selena Gomez, Marshmello",
"God's Plan - Drake",
"Rewrite The Stars - Zac Efron, Zendaya",
"Havana - Camila Cabello, Young Thug",
"Perfect - Ed Sheeran"
};
void ShowSong(int _val){
switch (_val) {
case 1: printf(song[0]);
break;
}
}
void Insert() {
int val;
printf("What song number you want to add : \n");
scanf("%d",val);
ShowSong(val);
printf("Added to playlist\n");
system("pause");
//ShowSong(val);
if (rear == NULL) {
rear = (struct node*) malloc(sizeof(struct node));
rear->next = NULL;
rear->data = val;
front = rear;
}
else {
temp = (struct node*) malloc(sizeof(struct node));
rear->next = temp;
temp->data = val;
temp->next = NULL;
rear = temp;
}
}
void NextSong() {
temp = front;
if (front == NULL) {
printf("Underflow");
system("pause");
return;
}
else
if (temp->next != NULL) {
temp = temp->next;
printf("\n");
printf("Skipping ",front->data );
int skipSongVal = front->data;
ShowSong(skipSongVal);
printf("\n");
free(front);
front = temp;
printf("\n");
printf("Now Playing ",front->data );
int nextSongVal = front->data;
ShowSong(nextSongVal);
printf("\n");
printf("\n");
system("pause");
}
else {
printf("Skipping ",front->data );
int nextSongVal2 = front->data;
ShowSong(nextSongVal2);
printf("\n");
free(front);
front = NULL;
rear = NULL;
system("pause");
}
}
void ClearPlaylist()
{
temp = front;
if (front == NULL) {
printf("Playlist is Already Empty\n");
system("pause");
return;
}
else
{
printf("Clearing Playlist");
free(front);
front = NULL;
rear = NULL;
system("pause");
}
}
void Display() {
printf("PLAYLIST ");
temp = front;
if ((front == NULL) && (rear == NULL)) {
printf("Playlist is empty\n");
return;
}
printf("Next Song is : \n");
while (temp != NULL) {
int valDisplay = temp->data;
printf("%d",valDisplay);
ShowSong(valDisplay);
printf("\n");
temp = temp->next;
}
printf("\n");
}
int main() {
int ch;
do {
system("CLS");
printf("MUSICS\n");
printf("1)\n",song[0]);
printf("2)\n",song[1]);
printf("3)\n",song[2]);
printf("4)\n",song[3]);
printf("5)\n",song[4]);
printf("6)\n",song[5]);
printf("7)\n",song[6]);
printf("8)\n",song[7]);
printf("9)\n",song[8]);
printf("10)\n",song[9]);
printf("\n");
Display();
printf("\n");
printf("1) Add Song to playlist\n");
printf("2) Skip to next song\n");
printf("3) Clear playlist\n");
printf("4) Exit\n");
printf("Enter your choice : \n");
scanf("%d",&ch);
switch (ch) {
case 1: Insert();
break;
case 2: NextSong();
break;
case 3: ClearPlaylist();
break;
case 4: printf("exit\n");
break;
default: printf("Invalid Choice");
}
} while (ch != 4);
return 0;
}
I'm having trouble deleting nodes in a doubly linked list, the program crash and i can't figure out the problem. Can you please help me?
This is the full code that creates new nodes, views them and deletes them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Test
{
int id;
};
typedef struct Node {
struct Test structure;
struct Node * next;
struct Node *prev;
}TNode;
typedef TNode* Node;
void NewNode(struct Test p, Node *pp)
{
Node temp;
temp = (Node)malloc(sizeof(struct Node));
temp->structure = p;
temp->next = *pp;
temp->prev = NULL;
if(*pp != NULL)
{
(*pp)->prev = temp;
}
*pp = temp;
}
void ReadStructure(struct Test * p)
{
printf("\nID:");
scanf(" %d", &p->id);
}
void ViewList(Node node)
{
Node temp;
while(node != NULL)
{
temp = node->prev;
if(node->prev == NULL)
{
printf("Prev = NULL\n");
}
else
{
printf("Prev: %d\n", temp->structure.id);
}
printf("Curr: %d\n", node->structure.id);
node = node->next;
}
}
void Delete(Node * head, Node del)
{
if(*head == NULL || del == NULL)
{
return;
}
if(*head == del)
{
*head = del->next;
}
if(del->next != NULL)
{
del->next->prev = del->prev;
}
if(del->prev != NULL)
{
del->prev->next = del->next;
}
free(del);
return;
}
int Menu()
{
int c;
printf("*** M E N U ***\n"
"1 - New Node\n"
"2 - View List\n"
"3 - Delete\n"
"0 - Exit\n"
"\n>> ");
scanf(" %d", &c);
return c;
}
int main()
{
int c;
struct Test test;
Node list = NULL;
Node del = NULL;
do {
c = Menu();
switch (c)
{
case 1: ReadStructure(&test);
NewNode(test, &list); break;
case 2: ViewList(list); break;
case 3: printf("\nElement to Delete: ");
scanf("%d", &del->structure.id);
Delete(&list, del); break;
default: c = 0;
}
} while (c != 0);
return 0;
}
I think the problem is related to the scanf() for the Node del, but i'm not sure. When i just pass list or list->next as second argument to the function Delete() it works. Is everything all right with the code?
int main()
{
...
Node del = NULL;
...
scanf("%d", &del->structure.id);
Your program should crash here. You are dereferencing a null pointer.
Probably you will need to read the user input into a temporary id variable, then search the list for a matching item, and if you find one, then you can try deleting it.
Ok, i added a function that searches for the node to be deleted and i modified a bit the Delete() function, this is the workaround, thank you for the suggestions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Test
{
int id;
};
typedef struct Node {
struct Test structure;
struct Node * next;
struct Node *prev;
}TNode;
typedef TNode* Node;
void NewNode(struct Test p, Node *pp)
{
Node temp;
temp = (Node)malloc(sizeof(struct Node));
temp->structure = p;
temp->next = *pp;
temp->prev = NULL;
if(*pp != NULL)
{
(*pp)->prev = temp;
}
*pp = temp;
}
void ReadStructure(struct Test * p)
{
printf("\nID:");
scanf(" %d", &p->id);
}
void ViewList(Node node)
{
Node temp;
while(node != NULL)
{
temp = node->prev;
if(node->prev == NULL)
{
printf("Prev = NULL\n");
}
else
{
printf("Prev: %d\n", temp->structure.id);
}
printf("Curr: %d\n", node->structure.id);
node = node->next;
}
}
Node SearchNode(Node head)
{
int d;
printf("\nElement to Delete:");
scanf("%d", &d);
while(head != NULL)
{
if(head->structure.id == d)
{
return head;
}
head = head->next;
}
printf("\nNo Element [%d] Found", d);
return NULL;
}
void Delete(Node * head, struct Test temp)
{
Node del = SearchNode(*head);
if(*head == NULL || del == NULL)
{
return;
}
if(*head == del)
{
*head = del->next;
}
if(del->next != NULL)
{
del->next->prev = del->prev;
}
if(del->prev != NULL)
{
del->prev->next = del->next;
}
free(del);
return;
}
int Menu()
{
int c;
printf("\n*** M E N U ***\n"
"1 - New Node\n"
"2 - View List\n"
"3 - Delete\n"
"0 - Exit\n"
"\n>> ");
scanf(" %d", &c);
return c;
}
int main()
{
int c;
struct Test test, del;
Node list = NULL;
do {
c = Menu();
switch (c)
{
case 1: ReadStructure(&test);
NewNode(test, &list); break;
case 2: ViewList(list); break;
case 3: Delete(&list, del); break;
default: c = 0;
}
} while (c != 0);
return 0;
}
del value is NULL, but you reference it when you delete.
What you need is to search a node in the list for the givent id and then delete it.
So I'm having issue with my code with the structure I'm using. I would like my structure to be able add,retrieve or sort but I'm getting a lot of problem with the structure. It work if I use only number but I need to user 3 string. One for firstname, lastname and phonenumber but I can't figure.
This is the code I'm having right now:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
char first[15];
char last[15];
char phone[12];
struct node *next;
}*head;
void append(int num, char f[15], char l[15],char p[12])
{
struct node *temp, *right;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
strcpy(temp->first, f);
strcpy(temp->last, l);
strcpy(temp->phone, p);
right = (struct node *)head;
while (right->next != NULL)
right = right->next;
right->next = temp;
right = temp;
right->next = NULL;
}
void add(int num, char f[15], char l[15],char p[12])
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
strcpy(temp->first, f);
strcpy(temp->last, l);
strcpy(temp->phone, p);
if (head == NULL)
{
head = temp;
head->next = NULL;
}
else
{
temp->next = head;
head = temp;
}
}
void addafter(int num, char f[15], char l[15],char p[12],int loc)
{
int i;
struct node *temp, *left, *right;
right = head;
for (i = 1; i<loc; i++)
{
left = right;
right = right->next;
}
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
strcpy(temp->first, f);
strcpy(temp->last, l);
strcpy(temp->phone, p);
left->next = temp;
left = temp;
left->next = right;
return;
}
void insert(int num, char f[15], char l[15],char p[12])
{
int c = 0;
struct node *temp;
temp = head;
if (temp == NULL)
{
add(num,f,l,p);
}
else
{
while (temp != NULL)
{
if (temp->data<num)
c++;
temp = temp->next;
}
if (c == 0)
add(num,f,l,p);
else if (c<count())
addafter(num,f,l,p, ++c);
else
append(num,f,l,p);
}
}
int delete(int num)
{
struct node *temp, *prev;
temp = head;
while (temp != NULL)
{
if (temp->data == num)
{
if (temp == head)
{
head = temp->next;
free(temp);
return 1;
}
else
{
prev->next = temp->next;
free(temp);
return 1;
}
}
else
{
prev = temp;
temp = temp->next;
}
}
return 0;
}
void display(struct node *r)
{
r = head;
if (r == NULL)
{
return;
}
while (r != NULL)
{
printf("%d ", r->data);
r = r->next;
}
printf("\n");
}
int count()
{
struct node *n;
int c = 0;
n = head;
while (n != NULL)
{
n = n->next;
c++;
}
return c;
}
int main()
{
int i, num;
char fname[15], lname[15], phone[12];
struct node *n;
head = NULL;
while (1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Retrieve\n");
printf("4.Delete\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if (scanf("%d", &i) <= 0){
printf("Enter only an Integer\n");
exit(0);
}
else {
switch (i)
{
case 1:
printf("Enter the id, first, last and phone (Separte with space) : ");
scanf("%d %s %s %s", &num,fname,lname,phone);
insert(num,fname,lname,phone);
break;
case 2:
if (head == NULL){
printf("List is Empty\n");
}else{
printf("Element(s) in the list are : ");
}
display(n);
break;
case 3:
//To be made
//scanf("Retrieve this : %d\n", count());
break;
case 4:
if (head == NULL){
printf("List is Empty\n");
}else{
printf("Enter the number to delete : ");
scanf("%d", &num);
if (delete(num))
printf("%d deleted successfully\n", num);
else
printf("%d not found in the list\n", num);
}
break;
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;
}
Thanks for anyone that could explain me the issue and or fix it.
Everywhere you have:
temp->data = num;
add the lines
strcpy(temp->first, f);
strcpy(temp->last, l);
strcpy(temp->phone, p);
I have written a linked list code to insert a element in the node. But the problem is when i want to insert first element using function, the output is coming empty. But when i insert first element inside the main function (see comment line), it gives the correct output. How to solve it ?
Here is my C code:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int val;
struct node *next;
}node;
void print(node *head){
if(tem == NULL){
printf("List is Empty\n");
return;
}
node *tem= head;
while(tem != NULL){
printf("%d ", tem->val);
tem= tem->next;
}
}
void insert(node *head, int val){
if(head == NULL){
node *tem= malloc(sizeof(node*));
tem->val= val;
tem->next= NULL;
head= tem;
return;
}
node *tem= head;
while(tem->next != NULL){
tem= tem->next;
}
tem->next= malloc(sizeof(node*));
tem->next->val = val;
tem->next->next= NULL;
}
int main()
{
node *head= NULL;
/*
head = malloc(sizeof(node*));
head->val= 5;
head->next= NULL;
*/
insert(head, 15);
print(head);
return 0;
}
Thanks
Try sending the address of the head instead of head as shown below:
insert(&head, 15);
void insert(node **head, int val){
if(*head == NULL){
node *tem= malloc(sizeof(node*));
tem->val= val;
tem->next= NULL;
*head= tem;
return;
}
This is because when you are sending the head, any changes made will be local to that function (insert in this case) and won't be reflected outside that function. Hence, you have to send the address of head (&head) so that changes made to head are reflected outside the function as well. Cheers
Try this completely implemented singly linked list:
#include <stdio.h>
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
void insert(int data, int position)
{
struct node *newNode=malloc(sizeof(struct node));
newNode->data=data;
if(position<1)
{
printf("Invalid Insertion Position \n");
return;
}
if(head==NULL && position==1)
{
newNode->next=NULL;
head=newNode;
}
else if(head==NULL && position!=1)
{
printf("Invalid Insertion Position \n");
}
else if(position==1)
{
newNode->next=head;
head=newNode;
}
else
{
int i=0;
struct node *temp=head;
while(temp->next!=NULL && i<position-2)
{
i++;
temp=temp->next;
}
if(i<position-2)
{
printf("Invalid Insertion Position \n");
}
else
{
newNode->next=temp->next;
temp->next=newNode;
}
}
}
void delete(int position)
{
int i=0;
if(position<1)
{
printf("Invalid Position of Deletion \n");
return;
}
if(head==NULL)
{
return;
}
if(position==1)
{
head=head->next;
}
else
{
struct node *temp=head;
while(temp->next->next!=NULL && i<position-2)
{
i++;
temp=temp->next;
}
if(i<position-2)
{
printf("Invalid Position of Deletion \n");
return;
}
else
{
temp->next=temp->next->next;
}
}
}
void printlist()
{
if(head==NULL)
{
printf("Empty List!! \n");
return;
}
struct node *temp=head;
while(temp!=NULL)
{
printf("%d",temp->data);
printf("\t");
temp=temp->next;
}
printf("\n");
}
int main()
{
int t;
printf("Enter number of Test Cases: \t");
scanf("%d", &t);
printf("\nEnter Queries in this format: \n");
printf("For Insertion: \t I data position \n");
printf("\tEx:\t I 25 5 \n");
printf("For Deletion: \t D position \n");
printf("\tEx:\t D 2 \n\n");
while(t--)
{
char c;
int a,b;
printf("Enter query: \t");
scanf("%c", &c);
scanf("%c", &c);
if(c=='I')
{
scanf("%d %d", &a,&b);
insert(a,b);
}
else if(c=='D')
{
scanf("%d", &a);
delete(a);
}
printlist();
}
}