I'm having a trouble with my school project. I was asked to use a linked list, I'm almost finish but then I got stuck in how do I sort my data by looking at the date
I want to display these data by sorting the date
I have searched everywhere and I still can't find how to sort a linked list multiple parameters
say these are the parameters:
struct Data {
int kode;
char variety[20];
int weight;
int date;
struct Data *next;
} *headIn, *tempIn;
with a main function like this:
int menu;
int pointIn = 0;
int amount = 0;
void insert(int kode, char *variety, int weight, int date);
void userInput();
void printList(struct Data *tempIn);
int main() {
headIn = NULL;
int menu = 0;
do {
system ("cls");
printf( " \n\nMAIN MENU :\n");
printf( " 1. Input Product\n\n");
printf( " 2. Print List\n\n");
printf( " enter your choice (1 - 2) : ");
scanf("%d", &menu);
if (menu < 1 || menu > 2) {
system("cls");
printf ("your input is not available\n");
getch();
}
switch (menu) {
case 1:
userInput();
break;
case 2:
printList(tempIn);
break;
}
}
while (menu != 3);
system("cls");
printf ("============ Thankyou ============");
return 0;
}
and then I apply this function so that the data is going to be a linked list:
void insert(int kode, char *variety, int weight, int date) {
struct Data *dataIn = (struct Data *)malloc(sizeof(struct Data));
dataIn->kode = kode;
strcpy(dataIn->variety, variety);
dataIn->weight = weight;
dataIn->date = date;
dataIn->next = NULL;
if (headIn == NULL) {
headIn = dataIn;
} else {
dataIn->next = headIn;
headIn = dataIn;
}
}
and then I have this 2 function for asking user's input and the other is for printing
void userInput() {
int code;
int weight;
int date;
amount = 0;
char variety[5][20] = { "Fish", "Crab", "Squid", "Clam", "Lobster" };
system ("cls");
printf("Number of data you want to enter : "); scanf("%d", &amount);
printf( "_________________________________________________________________\n");
printf("\n Kode 0 = Fish \n kode 1 = Crab \n kode 2 = Squid \n kode 3 = Clam \n kode 4 = Lobster\n\t\t\t ");
for (int i = 0; i < amount; i++) {
printf("\n\nProduct-%d", pointIn + 1);
printf("\n\tInput code\t : "); scanf(" %d", &code);
if (code < 0 || code > 4) {
printf ("this code product is not available\n");
i--;
} else {
printf("\tJenis\t\t : %s\n", variety[code]);
printf("\tINPUT weight\t : "); scanf(" %d", &weight );
printf("\tInput date (YYYYMMDD)\t : ");scanf(" %d", &date);
pointIn++;
insert(code, variety[code], weight, date);
}
}
getch();
}
void printList(struct Data *tempIn) {
system ("cls");
tempIn = headIn;
//sort function here
printf("***** DATA PRODUCT ***** \n" );
printf("| DATE | CODE | NAME | WEIGHT | \n");
while (tempIn != NULL) {
printf(" %d %d %s %d \n", tempIn->date, tempIn->kode, tempIn->variety, tempIn->weight);
tempIn = tempIn->next;
}
getch();
}
please help me I don't understand and I can't find any references, it's just this sorting part I'm stuck in.
In the Insert function, you must find the proper place to insert the node by iterating in the list past the nodes with a lesser date:
void insert(int kode, const char *variety, int weight, int date) {
struct Data *dataIn = (struct Data *)malloc(sizeof(struct Data));
if (dataIn == NULL) {
fprintf(stderr, "cannot allocate memory for Data struct\n");
return;
}
dataIn->kode = kode;
strcpy(dataIn->variety, variety);
dataIn->weight = weight;
dataIn->date = date;
if (headIn == NULL || headIn->date > date) {
// insert node at the head
dataIn->next = headIn;
headIn = dataIn;
} else {
// insert node in the list
struct Data *np = head;
while (np->next && np->next->date >= date) {
np = np->next;
}
dataIn->next = np->next;
np->next = dataIn;
}
}
I have solved my problem for sorting this program
first i add a new struct
struct node{
int kode;
char variety[20];
int weight;
int date;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node = (struct node*) malloc(sizeof(struct node));
node->date = data;
node->left = NULL;
node->right = NULL;
return(node);
}
and then i initiate an array
struct Data order[100];
int k=0;
and then make the sorting functions
struct node* insertSort(struct node* node, int data)
{
if (node == NULL)
return(newNode(data));
else
{
if (data <= node->date)
node->left = insertSort(node->left, data);
else
node->right = insertSort(node->right, data);
return node;
}
}
void sort(struct node* node) {
struct node* current = node;
if (node != NULL) {
sort (current->left);
order[k++].date =node->date ;
sort (current->right);
}
}
and then i update my printing process so that it can print the sorted products
void printList(struct Data *tempIn) {
system ("cls");
tempIn = headIn;
int angka =0;
struct node* root = NULL;
while(tempIn!=NULL){
if(root==NULL){
root = insertSort(root, tempIn->date);
}
else {
insertSort(root, tempIn->date);
}
tempIn = tempIn->next;
}
tempIn = headIn;
printf("***** DATA PRODUCT ***** \n" );
printf("| DATE | CODE | NAME | WEIGHT | \n");
k=0;
for (int i=0;i<100;i++){
order[i].date=0;
order[i].kode =0;
order[i].weight=0;
}
sort(root);
tempIn = headIn;
for(int i=0;i<100;i++){
tempIn = headIn;
while (tempIn != NULL) {
if(order[i].date==tempIn->date){
printf(" %d %d %-10s %d \n", tempIn->date, tempIn->kode, tempIn->variety, tempIn->weight);
}
tempIn = tempIn->next;
}
}
getch();
}
Related
EDIT: This question has not received any feedback in a few days and I would like to ask if there are any unclear parts that I could improve in the description so you could attempt answering without hesitation. Thank you.
The program given below, groups the input in two different tables based on the gender and should sort the data by age in descending order. See below for more explanation:
Insert the code of the person Number 1: 1
Insert the age of the person Number 1: 1
Insert the gender of the person Number 1: 1
Insert the code of the person Number 2: 2
Insert the age of the person Number 2: 2
Insert the gender of the person Number 2: 1
Insert the code of the person Number 3: 3
Insert the age of the person Number 3: 3
Insert the gender of the person Number 3: 1
Insert the code of the person Number 4: 4
Insert the age of the person Number 4: 2
Insert the gender of the person Number 4: 0
Insert the code of the person Number 5: 5
Insert the age of the person Number 5: 3
Insert the gender of the person Number 5: 0
And the result is the following:
Men
Code Age Gender
3 3 1
1 1 1
2 2 1
Women
Code Age Gender
4 2 0
5 3 0
The proper result should be the following (hint: Sorted by Age):
Men
Code Age Gender
3 3 1
2 2 1
1 1 1
Women
Code Age Gender
5 3 0
4 2 0
-NOTES-
The issue is probably only in the sort_List() function and it is needed to include the first node of two lists in a sorting function.
How can the sortList() be modified to work correctly?
The code is displayed below:
#include <stdio.h>
#include <stdlib.h>
typedef struct people
{ /* a struct for people*/
int code; /* a unique identifier for each person*/
int age;
int gender;
struct people *next;
} ppl;
ppl *make_ppl(int code, int age, int gender, ppl *next)
{
ppl *p = malloc( sizeof(struct people) ); //as suggested in the comments
p->code = code;
p->age = age;
p->gender = gender;
p->next = next;
return p;
}
// a function to insert nodes
void insertFirst(ppl **ppHead, int code, int age, int gender)
{
*ppHead = make_ppl(code, age, gender, *ppHead);
}
void sortList() {
//Node current will point to head
int head;
ppl *current = head, *index = NULL;
int temp;
if(head == NULL) {
return;
}
else {
while(current != NULL) {
//Node index will point to node next to current
index = current->next;
while(index != NULL) {
//If current node's data is greater than index's node data, swap the data between them
if(current->age < index->age) {
temp = current-> age;
current->age = index->age;
index->age = temp;
temp = current-> code;
current->code = index->code;
index->code = temp;
temp = current-> gender;
current->gender = index->gender;
index->gender = temp;
}
index = index->next;
}
current = current->next;
}
}
}
// display the list
void printList(const char *title, ppl const *head)
{
sortList();
static const char *myStrings[] = {"Code", "Age", "Gender"};
static const size_t n_strings = sizeof myStrings / sizeof *myStrings;
int i;
puts(title);
for (i=0; i<n_strings; ++i)
printf("\t%s", myStrings[i]);
fputc('\n', stdout);
// start from the beginning
while (head != NULL)
{
printf("\t%d\t%d\t%d\n", head->code, head->age, head->gender);
head = head->next;
}
}
and then the main() is below:
int main()
{
int i;
ppl *z1 = NULL;
ppl *z2 = NULL;
int code1, age1, gender1;
for (i = 1; i <= 3; i++)
{
printf("Insert the code of the person Number %d: ", i);
scanf("%d", &code1);
printf("Insert the age of the person Number %d: ", i);
scanf("%d", &age1);
printf("Insert the gender of the person Number %d: ", i);
scanf("%d", &gender1);
if (gender1 == 1)
insertFirst(&z1, code1, age1, gender1); // Here it stores in z1 for men
else
insertFirst(&z2, code1, age1, gender1); // Here it stores in z2 for women
}
printList("Men", z1);
printList("Women", z2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct people
{ /* a struct for people*/
int code; /* a unique identifier for each person*/
int age;
int gender;
struct people *next;
} ppl;
ppl *make_ppl(int code, int age, int gender, ppl *next)
{
ppl *p = malloc( sizeof(struct people) );;
p->code = code;
p->age = age;
p->gender = gender;
p->next = next;
return p;
}
// a function to insert nodes
void insertFirst(ppl **ppHead, int code, int age, int gender)
{
*ppHead = make_ppl(code, age, gender, *ppHead);
}
void sortList(ppl *head) {
//Node current will point to head
ppl *current = head, *index = NULL;
int temp;
if(head == NULL) {
return;
}
else {
while(current != NULL) {
//Node index will point to node next to current
index = current->next;
while(index != NULL) {
//If current node's data is greater than index's node data, swap the data between them
if(current->age < index->age) {
temp = current-> age;
current->age = index->age;
index->age = temp;
temp = current-> code;
current->code = index->code;
index->code = temp;
temp = current-> gender;
current->gender = index->gender;
index->gender = temp;
}
index = index->next;
}
current = current->next;
}
}
}
// display the list
void printList(const char *title, ppl *head)
{
static const char *myStrings[] = {"Code", "Age", "Gender"};
static const size_t n_strings = sizeof myStrings / sizeof *myStrings;
sortList(head);
int i;
puts(title);
for (i=0; i<n_strings; ++i)
printf("\t%s", myStrings[i]);
fputc('\n', stdout);
// start from the beginning
while (head != NULL)
{
printf("\t%d\t%d\t%d\n", head->code, head->age, head->gender);
head = head->next;
}
}
void deleteList(ppl **ppHead)
{
while (*ppHead)
{
ppl *p = *ppHead;
*ppHead = p->next;
free(p);
}
}
int main()
{
int i;
ppl *z1 = NULL;
ppl *z2 = NULL;
int code1, age1, gender1;
for (i = 1; i <= 6; i++)
{
printf("Insert the code of the person Number %d: ", i);
scanf("%d", &code1);
printf("Insert the age of the person Number %d: ", i);
scanf("%d", &age1);
printf("Insert the gender of the person Number %d: ", i);
scanf("%d", &gender1);
if (gender1 == 1)
insertFirst(&z1, code1, age1, gender1); // Here it stores in z1 for men
else
insertFirst(&z2, code1, age1, gender1); // Here it stores in z2 for women
}
printList("Men", z1);
printList("Women", z2);
return 0;
}
I have been getting Thread 1 : EXC_BAD_ACCESS error when trying to push a string element into the stack. I've changed the char* name to char name[21] but the assignment char[21] is not assignable to curr->name. Also I've tried fgets but the error still there. Anyone know where the error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct parts
{
char* name;
char* type;
int quantity;
int price;
int num;
struct parts * next;
}*head,*tail,*curr,komponen;
void menu();
void show_Parts();
void push(char* nm, char* tip, int jml, int harga, int nom);
void del();
int main() {
menu();
del();
getchar();
return 0;
}
void push(char* nm, char* tip, int jml, int harga, int nom)
{
// 1.
curr = (struct parts *)malloc(sizeof(struct parts));
// 2.
if (curr == NULL) {
exit(0);
}
head = NULL;
head = curr->next;
curr->name = nm;
curr->type = tip;
curr->quantity = jml;
curr->price = harga;
curr->num = nom;
curr = head;
//
printf("Input name of the new item [3..20]: ");
scanf("%s",nm);
if (strlen(nm) < 3 || strlen(nm) > 20) {
printf("Length of name must between 3 and 20");
exit(0);
}
printf("Input type of the new item [processor/graphic card/memory]: ");
scanf("%s",tip);
if (tip != "processor" || tip != "graphic card" || tip != "memory") {
printf("Input type of existing item. Error");
exit(0);
}
printf("Input quantity of the new item [1..20]: ");
scanf("%d",&jml);
if (jml < 1 || jml > 20) {
printf("Quantity between 1 and 20\n");
exit(0);
}
printf("Input price of new item [$1..$1000]: ");
scanf("%d",&harga);
if (harga < 1 || harga > 1000) {
printf("Price between 1 and 1000\n");
exit(0);
}
nom++;
printf("--- Add New Item Success ---\n");
tail->next = NULL;
}
void del()
{
if (curr == NULL) {
exit(0);
}
curr = head;
head = head->next;
free(curr);
}
void menu()
{
int choic;
do {
printf("BLUE COMPUTER ADMINISTRATOR\n");
printf("++++++++++++++++++++++++++++\n");
printf("1. Item list\n");
printf("2. Add <PUSH> New item\n");
printf("3. Exit\n");
printf(">> Input your choice : ");
switch (choic) {
case 1:
show_Parts();
break;
case 2:
push(komponen.name,komponen.type,komponen.price, komponen.quantity, komponen.num);
break;
case 3:
del();
exit(0);
break;
}
scanf("%d",&choic);
} while (choic != 3);
}
void show_Parts()
{
if (curr == NULL) {
printf("No item in list\n");
exit(0);
}
printf(" ---- ITEM LIST ---- \n\n");
printf("-----+------------------+--------+-----------+--------\n");
printf("|No. | Name | Type | Quantity | Price|\n");
do {
printf("|%d |%s |%s |%d |%d \n",curr->num, curr->name, curr->type, curr->quantity, curr->price);
curr = curr->next;
}while (curr != NULL);
}
Thanks.
#include <stdio.h>
#include <stdlib.h>
typedef struct nodeNum
{
int num;
struct nodeNum *next;
} t_nodeNum;
// Functions declaration ----------------------------
int menu(); // display menu and return choice
t_nodeNum* addition(t_nodeNum *node, int n);
void print_list(t_nodeNum *node);
// ----------------------------------------------------
// Main program to test link list functions
int main()
{
int choice;
t_nodeNum *pnode = NULL;
t_nodeNum *head = NULL;
t_nodeNum *temp = NULL;
int numAdd = 0;
int len = 0;
int first = 1;
do
{
choice = menu();
switch (choice)
{
case 1:
{
printf("Please enter number : \n");
scanf("%d", &numAdd);
if (first)
{
pnode = (t_nodeNum *)malloc(sizeof(t_nodeNum));
if (pnode == NULL)
{
printf("\n Error in allocation\n");
exit(0);
}
pnode->num = numAdd;
pnode->next = NULL;
first = 0;
head = pnode;
}
pnode = addition(pnode, numAdd);
break;
}
case 4:
{
printf("\n Print List: ");
print_list(head);
break;
}
}
}
while (choice != 5);
return 0;
}
// function menu display menu and return choice
int menu()
{
int choice = 0;
do
{
printf("Please choose option to do: \n");
printf("1. addition\n");
printf("2. deletion\n");
printf("3. search\n");
printf("4. print\n");
printf("5. exit\n");
printf("\n option = ");
scanf("%d", &choice);
}
while (choice < 1 || choice > 5);
return choice;
}
// function addition to add item to linked list in recursion
t_nodeNum* addition(t_nodeNum *p, int numAdd)
{
int len = 0;
if (p == NULL)
{
p = (t_nodeNum *)malloc(sizeof(t_nodeNum));
if (p == NULL)
{
printf("\n Error in allocation\n");
exit(0);
}
p->num = numAdd;
p->next = NULL;
}
else
{
p = addition(p->next, numAdd);
}
return (p);
}
// function print_list to print linked list in recursion
void print_list(t_nodeNum *head)
{
printf("%d ", head->num);
if (head->next == NULL)
{
printf("\n");
return;
}
print_list(head->next);
}
There is problem with the addition function it does not work correctly to add new item to the linked list and I does not know what is wrong please help
After adding new items and do print list it display only the first item
In you main function -
pnode = addition(pnode, numAdd);
instead of pnode you need to pass pnode->next -
pnode = addition(pnode->next, numAdd);
Problem with first call is that pnode is not NULL so it just adds new element at head position replacing previous value and returns.
Therefore, new node is not being created.
When I running this code and call " List() "function it prints only the last added by user . I want to print from beginning to the end.I hope you will help me about my list function.It prints only the last one.
#include<stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
struct seat {
int k_no;
int k_name;
struct seat *next_k, *previous_k;
} *first_k, *temp_k, *last_k;
struct sefer {
char name[20];
int no;
struct sefer *next, *previous;
struct seat *bus;
} *first, *last, *temp;
void list();
void seat_link(int val);
void sefer_search();
int main() {
int val;
printf ("how many names do you want to type ->");
scanf ("%d", &val);
int i;
int j;
for (i = 0; i < val; i++) {
if (first == NULL) {
first = (sefer *)malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name->", i + 1);
scanf("%s", &first->name);
printf(" %d. capacity ->", i + 1);
scanf("%d", &first->no);
first->next = NULL; //2 inci düğüm daha oluşmadığı için null
first->previous = NULL;
last = first; //şimdilik sadece ilk düğüm olduğu için aynı zamanda son oluo
last->bus = NULL;
for (j = 0; j < first->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 1;
first_k->next_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat ));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->last_k = NULL;
}
}
} else if (last == first) {
printf("\n");
last = (sefer *)malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name ->", i + 1);
scanf("%s", &last->name);
printf(" %d. capacitiy ->", i + 1);
scanf("%d", &last->no);
first->next = last;
last>next = NULL;
last->previous = first;
last->bus = NULL;
for (j = 0; j < last->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat *)malloc(sizeof(struct seat ));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 2;
first_k->last_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->last_k = NULL;
}
}
} else { // kayıt eklenmişse diğer düğümler oluşturulcak
printf ("\n");
temp = (sefer *) malloc(sizeof(struct sefer));
fflush(stdin);
printf(" %d. name", i + 1);
scanf("%s", &temp->name);
printf(" %d. capacity->", i + 1);
scanf("%d", &temp->no);
last->next = temp;
temp->previous = last;
last = temp;
last->next = NULL;
last->bus = NULL;
for (j = 0; j < temp->no; j++) {
//KOLTUKLAR OLUŞTURULCAK
if (last->bus == NULL) {
first_k = (seat*)malloc(sizeof(struct seat));
fflush(stdin);
first_k->k_no = j;
first_k->k_name = 3;
first_k->last_k = NULL;
first_k->previous_k = NULL;
last_k = first_k;
last->bus = first_k;
} else {
temp_k = (seat *)malloc(sizeof(struct seat));
fflush(stdin);
temp_k->k_no = j;
temp_k->k_name = 0;
last_k->next_k = temp_k;
temp_k->previous_k = last_k;
last_k = temp_k;
last_k->next_k = NULL;
}
}
}
}
list();
system("PAUSE");
return 0;
}
void sefer_search() { //bağda arama yapar
int searching;
printf("\n\t\t Aranacak Sefer Numarasını Giriniz:");
scanf("%d", &searching);
temp = first;
while (1) {
if (temp->no == searching) {
break;
}
temp = temp->next;
}
}
void seat_link(int val) {
int j;
}
my problem is here actually :
void list() {
temp = first;
while (temp != NULL) {
printf("\t%s --%d \n", temp->name, temp->no);
temp = temp->next;
}
printf ("\n");
last->bus = first_k;
while (last->bus != NULL) {
printf("\t%d --%d \n", last->bus->k_name, last->otobus->k_no);
last->bus = last->bus->next_k;
}
}
Please help me
There are a bunch of problems with your code. Firstly, it won't compile for various reasons. For instance, you sometimes use a struct koltuk without ever defining it. "koltuk" means "seat" in Turkish, so I'm going to assume you meant struct seat in all those cases. Secondly, deg is undefined; I assume you meant val.
There were a few other problems like that which I was able to fix by making plausible guesses. But that leaves the following fundamental problems:
You are using global variables as local variables, for instance temp_k and temp. This makes it well-nigh impossible for a human to analyze your code and understand the control flow.
You have copied code all over the place. You have three separate code blocks to allocate and initialize a sefer depending upon whether it's first in the global linked list, second, or later. Use subroutines!
Your data model seems confused. You have global variables struct *first_k,*temp_k,*last_k; which makes it seem like you have one global linked list of seats for all sefer structs, but the struct seat does not refer back in an obvious way to the sefer that owns it, which implies that each sefer has a separate, private list of seats.
Taking all three problems together, I can't really see where, specifically, you are going wrong. I took a cut at rewriting your code to eliminate these problems. Give it a try to see if it solves your problems:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct seat{
int k_no;
int k_name;
struct seat *next_k, *previous_k;
} seat;
typedef struct sefer {
char name[20];
int no;
struct sefer *next,*previous;
struct seat *bus;
} sefer;
void list();
sefer *sefer_search();
void link_sefer(sefer **pp_first, sefer **pp_last, sefer *p_added)
{
p_added->next = p_added->previous = NULL;
if (*pp_first == NULL)
{
*pp_first = *pp_last = p_added;
}
else
{
(*pp_last)->next = p_added;
p_added->previous = *pp_last;
*pp_last = p_added;
}
}
void link_seat(seat **pp_first, seat **pp_last, seat *p_added)
{
p_added->next_k = p_added->previous_k = NULL;
if (*pp_first == NULL)
{
*pp_first = *pp_last = p_added;
}
else
{
(*pp_last)->next_k = p_added;
p_added->previous_k = *pp_last;
*pp_last = p_added;
}
}
sefer *create_and_link_sefer(sefer **pp_first_sefer, sefer **pp_last_sefer, int i)
{
sefer *new_sefer;
seat *p_first_seat = NULL;
seat *p_last_seat = NULL;
int j;
// Allocate and initialize sefer
printf ("\n");
new_sefer = calloc(1, sizeof(struct sefer));
fflush(stdin);
printf (" %d. name->",i+1);
scanf ("%s",&new_sefer->name);
printf (" %d. capacity->",i+1);
scanf ("%d",&new_sefer->no);
new_sefer->bus = NULL;
// Link sefer
link_sefer(pp_first_sefer, pp_last_sefer, new_sefer);
// Allocate seats
for(j=0;j<new_sefer->no;j++){
//KOLTUKLAR OLUŞTURULCAK
seat *p_seat = calloc(1, sizeof(struct seat));
fflush(stdin);
p_seat->k_no=j;
p_seat->k_name = (j != 0 ? 0 : (i+1 > 3 ? 3 : i+1)); // I CAN'T FIGURE OUT WHAT THIS IS SUPPOSED TO BE
link_seat(&p_first_seat, &p_last_seat, p_seat);
}
new_sefer->bus = p_first_seat;
return new_sefer;
}
void sefer_list(sefer *first, sefer *last){
sefer *temp=first;
while (temp !=NULL)
{
seat *seat;
printf("\t%s --%d \n", temp->name,temp->no);
for (seat = temp->bus; seat != NULL; seat = seat->next_k)
{
printf("\t\t%d --%d \n",seat->k_name, seat->k_no);
}
printf ("\n");
temp=temp->next;
}
}
sefer *sefer_search(sefer *first, sefer *last){ //bağda arama yapar
int arama;
sefer *temp;
printf ("\n\t\t Aranacak Sefer Numarasını Giriniz:");
scanf ("%d",&arama);
temp=first;
while (temp != NULL){
if (temp->no==arama){
break;
}
temp=temp->next;
}
return temp;
}
sefer *first = NULL;
sefer *last = NULL;
int main( )
{
int val;
int i;
printf ("how many names do you want to type ->");
scanf ("%d",&val);
for(i=0;i<val;i++){
create_and_link_sefer(&first, &last, i);
}
sefer_list(first, last);
system("PAUSE");
return 0;
}
It seems to work, but since I don't know what you are trying to do, it might not be working as you want.
Judging by the logic, that means that temp really isn't going anywhere. My guess is that when you set those pointers *first, *last, *temp; in the first few lines of main, you don't really point first to NULL, causing it to skip the first if statement. Pointers don't point to NULL by default, they point to whatever was at that memory location beforehand. In this case, garbage. Try adding first=NULL; prior to your first if-statement.
I am coding for a simple linked list , but facing a little problem. The program is like it is accepting name, age and DOB through user, and memory for it is dynamically allocated. After taking data from the user, it is searching a name, asked by user, if the name exists, it should print all the details related to it.
Here is my code-
//function declarations
struct node *initnode(char *, char *, char *);
void add(struct node *);
struct node *printnode(struct node *);
struct node *searchname(struct node *, char *);
struct node {
char name[25];
char age[10];
char dob[10];
struct node *next;
};
struct node *head = (struct node *) NULL;
struct node *initnode(char *name, char *age, char *dob1)
{
struct node *ptr;
ptr = (struct node *) malloc(sizeof(struct node));
if (ptr == NULL)
return (struct node *) NULL;
else {
strcpy(ptr->name, name);
strcpy(ptr->age, age);
strcpy(ptr->dob, dob1);
ptr->next = NULL;
return ptr;
}
}
struct node *printnode(struct node *ptr)
{
printf("Name -> %s\n", ptr->name);
printf("age -> %s \n", ptr->age);
printf("dob ->%s\n", ptr->dob);
return ptr;
}
void add(struct node *newp)
{
struct node *temp = (struct node *) malloc(sizeof(struct node));
if (head == NULL)
head = newp;
else {
for (temp = head; temp->next != NULL; temp = temp->next);
temp->next = newp;
temp = newp;
}
free(temp);
}
struct node *searchname(struct node *ptr, char *name1)
{
if (strcmp(name1, ptr->name) == 0) {
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else {
printf("\n name not found in the database \n");
}
}
int main()
{
char name[25];
char name1[25];
char rep;
char age[10];
char dob[10];
int i;
int flag = 1;
struct node *ptr;
do {
fflush(stdin);
while (flag != 0) {
printf("Enter name -- ");
gets(name);
for (i = 0; name[i] != '\0'; i++)
if (isdigit(name[i])) {
printf("Error in user input, name should be in alphabets\n");
flag = 1;
break;
}
else
flag = 0;
}
flag = 1;
while (flag != 0) {
printf("Enter age -- ");
scanf("%s", &age);
fflush(stdin);
for (i = 0; age[i] != '\0'; i++)
if (isalpha(age[i])) {
printf("Error in user input, age should be in numbers\n");
flag = 1;
break;
} else {
flag = 0;
}
}
flag = 1;
while (flag != 0) {
printf("Enter dob in DD/MM/YY format-- ");
scanf("%s", &dob);
fflush(stdin);
for (i = 0; dob[i] != '\0'; i++) {
if (isalpha(dob[i])) {
printf("Error in user input, dob should be in numbers\n");
flag = 1;
break;
} else
flag = 0;
}
}
flag = 1;
ptr = initnode(name, age, dob);
add(ptr);
printf("\n Do you want to continue?<Y/N>:\n ");
scanf("%s", &rep);
//rep = getchar();
}
while (rep == 'Y' || rep == 'y');
printf("\n do u want to search for a name in the database? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
do {
printf("\n do u want to search again? <Y/N>:\n");
scanf("%s", &rep);
if (rep == 'Y' || rep == 'y') {
printf("Enter name you want to search-- ");
scanf("%s", &name1);
ptr = searchname(head, name1);
} else {
printf("\n goodbye \n");
}
}
while (rep == 'Y' || rep == 'y');
return 0;
}
The issue is that it is searching for the first entry only and not others, can anyone help me to sort out this? I am compiling through "gcc".
At a first glance, your search function is only comparing one element, the head of the list.
After comparing one element you must go to the next element. This can either be done recursively or with a while:
Recursive use:
struct node *searchname(struct node *ptr, char *name1)
{
if (ptr==NULL) //Reached end of the list
{
printf("\n name not found in the database \n");
return NULL;
}
if (strcmp(name1, ptr->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(ptr);
return ptr;
} else { //search next element
return searchname(ptr->next,name1); //this will call your function again for the next element on the list
}
}
While use:
struct node *searchname(struct node *ptr, char *name1)
{
struct node *aux; // usually i use an auxiliary pointer in order to avoid unwanted overwrite at my pointer.
aux = ptr;
while (aux!=NULL)
{
if (strcmp(name1, aux->name) == 0) { //found the element
printf("\n name found \n");
printf("\n details are -\n");
printnode(aux);
return aux;
}
else { //move pointer to next element
aux=aux->next;
}
}
//if it reaches this point, the element was not found
printf("\n name not found in the database \n");
return NULL;
}
Check your add function, it is wrong. Step mentally through it, and see what happens
to your pointer, and to the memory it points to.
What are the malloc and free used for in the add function?