Related
I am trying to creat a linked list in c language,
the code compiles with no error but when I run it , it won't run.
the data structure is a task which contains the label it's number, duration , number of linked tasks which will be put in an array and a pointer to the next task.
here's my code and the test code
#include <stdio.h>
#include <stdlib.h>
typedef struct tache { //linked listes structure
char label;
int num; //task number
int dure;
int *inter;
int n; //nombre d'antécedents
struct tache * suivant;
}strTache,*pTask;
pTask creerVide(){ //créer une tache vide
return NULL;
}
pTask firstTask(int d){
//créer la première tache qui prend la durée en argument
pTask first = (strTache*)(malloc(sizeof(strTache)));
first->num = 1;
first->suivant = NULL;
first->label = 'A';
first->dure = d;
first->n = 0;
return first;
}
Bool vide(pTask t){return t==NULL;} //check if a liste of tasks is empty this is predefined in a header included in the program
pTask ajouteTask(pTask t, int d){
pTask new = (strTache*)(malloc(sizeof(strTache)));
if(vide(t)){
new = firstTask(d);
t->suivant = new;
}else
{
pTask parc = t;
while(parc->suivant != NULL){parc=parc->suivant;}
new->num = parc->num+1;
new->label = parc->label+1;
new->suivant = parc->suivant;
parc->suivant = new;
new->dure=d;
}
return new;
}
void ajouteInter(pTask p,int numero, int taille, int tab[]){
int i,j;
pTask move = p;
while(move->suivant!=NULL){
if(move->num != numero){
move=move->suivant;
}//fin if
else
{
move->inter = (int*) malloc(taille*sizeof(int));
move->n = taille;
}//fin else
}//fin while
for(i=0;i<taille;i++){
move->inter[i] = tab[i];
}//fin for
}//fin function
void affichmat2(pTask p){
int i = 0;
pTask parc = p;
while(parc!= NULL){
printf("la tache %c a %d antécédents : ",parc->label,parc->n);
for(int j=0;j<parc->n;j++){
printf("%d ",parc->inter[j]);
}
printf("\n");
parc=parc->suivant;
i++;
}
free(parc);
}
int main()
{
int b[1] = {1};
int c[2] = {1,2};
//pTask t1 = creerVide();
pTask t1 = firstTask(2);
pTask t2,t3;
t2 = ajouteTask(t1,3);
t3 = ajouteTask(t2,4);
ajouteInter(t2,2,1,b);
ajouteInter(t3,3,2,c);
affichmat2(t1);
return 0;
}
I have made some changes thanks to your advice:
the function ajoutetask which called now addtask:
,,,
pTask addTask(pTask t, int d){
pTask new;
if(vide(t)){
new = firstTask(d);
new->suivant = t;
}else
{
new = (strTache*)(malloc(sizeof(strTache)));
pTask parc = t;
while(parc->suivant != NULL){parc=parc->suivant;}
new->num = parc->num+1;
new->label = parc->label+1;
new->suivant = parc->suivant;
parc->suivant = new;
new->dure=d;
}
return new;
}
,,,
the function ajouteinter which called now add antecedent:
void addAntecedent(pTask p,int num, int size, int b[]){
pTask search = p;
while(search->num !=num){
search = search->suivant;
}
search->inter = (int*)malloc(sizeof(int)*size);
search->n = size;
for(int i = 0;i<size;i++){
search->inter[i] = b[i];
}
}
the changes to the test file :
int main (){
int b[1] = {1};
int c[2] = {1,2};
pTask t1 = firstTask(2);
pTask t2,t3;
t2 = addTask(t1,3);
t3 = addTask(t1,4);
addAntecedent(t1,2,1,b);
addAntecedent(t1,3,2,c);
affichmat2(t1);
return 0;
}
the code works properly now
the result :
la tache A a 0 antécédents :
la tache B a 1 antécédents : 1
la tache C a 2 antécédents : 1 2
For starters use English words for identifiers.
Your code does not make a sense.
Consider for example the function ajouteTask
pTask ajouteTask(pTask t, int d){
pTask new = (strTache*)(malloc(sizeof(strTache)));
if(vide(t)){
new = firstTask(d);
t->suivant = new;
//...
If the pointer t is equal to NULL (that is when the function vide returns 1) then 1) the function invokes undefined behavior due to this statement
t->suivant = new;
and 2) it produces a memory leak because at first a memory was allocated and its address was assigned to the pointer new
pTask new = (strTache*)(malloc(sizeof(strTache)));
and then the pointer was reassigned
new = firstTask(d);
Or within the function ajouteInter you have an infinite while loop if move->num is equal to numero
void ajouteInter(pTask p,int numero, int taille, int tab[]){
int i,j;
pTask move = p;
while(move->suivant!=NULL){
if(move->num != numero){
move=move->suivant;
}//fin if
else
{
move->inter = (int*) malloc(taille*sizeof(int));
move->n = taille;
}//fin else
}//fin while
//...
So what you need is to rework your code and if there will be problems ask a new question.
Click here
https://uniblogsp.blogspot.com/2022/05/link-list-implementation-in-c-insertion.html
#include <stdio.h>
#include <stdlib.h>
typedef struct intnode
{
int data;
struct intnode *next;
} intnode;
intnode *create(int n)
{
intnode *head, *q, *newnode;
head = (intnode *)malloc(sizeof(intnode));
scanf("%d", &head->data);
head->next = NULL;
q = head;
for (int i = 0; i < n - 1; i++)
{
newnode = (intnode *)malloc(sizeof(intnode));
scanf("%d", &newnode->data);
newnode->next = NULL;
q->next = newnode;
q = newnode;
}
return head;
}
void printList(intnode *head)
{
intnode *temp;
temp = head;
while (head != NULL)
{
printf("%d", head->data);
head = head->next;
printf("\n");
}
head = temp;
}
void insertList(intnode *head, int i, intnode *t)
{
intnode *r, *x;
if (i == 0)
{
t->next = head;
head = t;
return;
}
r = head;
for (int j = 1; (j < i - 1) && (r != NULL); j++)
{
r = r->next;
}
if ((r == NULL) && (i > 0))
{
return;
}
x = r;
t->next = x->next;
x->next = t;
return;
}
void deleteList(intnode *head, int i)
{
intnode *y, *x;
y = head;
if (i == 0)
{
head = head->next;
free(y);
return;
}
x = y->next;
for (int j = 1; (j < i) && (x != NULL); i++)
{
y = x;
x = x->next;
}
if ((x == NULL) && (i > 0))
{
return;
}
y->next = x->next;
x->next = NULL;
free(x);
return;
}
int main()
{
int n, l;
printf("Enter the no of nodes: \n");
scanf("%d", &n);
printf("Enter the elements of nodes: \n");
intnode *p = create(n);
printf("Nodes are: \n");
printList(p);
printf("If you want to insert node then press 1 and in case of delete node press 0 : \n");
int ans;
scanf("%d", &ans);
if (ans == 1)
{
printf("In what positiomn you want to insert the node ??\n");
scanf("%d", &l);
intnode *a;
a = (intnode *)malloc(sizeof(intnode));
printf("Enter the node data :\n");
scanf("%d", &a->data);
a->next = NULL;
insertList(p, l, a);
printf("After insertion the list is : \n");
printList(p);
}
else
{
printf("In what positiomn you want to delete the node ??\n");
scanf("%d", &l);
deleteList(p, l);
printf("After deletion the list is : \n");
printList(p);
}
return 0;
}
I wanted to evaluate a polynome for a given value so I have used a linked list to store the coefficients and the exponants,and I have defined a function evaluate() to evaluate the polynome for a given value, but I do have a problem when it comes to the output it always shows the value 0.00000
can I get some help ? thanks in advance.
here's the full code :
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int coef;
int expo;
struct list* next;
}list;
int compare(char* s1,char* s2)
{
int i=0;
char c1,c2;
do
{
c1= (*(s1+i));
c2= (*(s2+i));
i++;
if(c2 == '\0' || c1 == '\0')
return c1-c2;
}while(c1==c2);
return c1-c2;
}
int transform(char* arr)
{
int i,sign=0;
int s=0;
if((*arr) == '-') sign=1;
for(i=0;arr[i]!='\0';i++)
{
if(arr[i]>=0 && arr[i]<=9)
s=s*10+(arr[i]-'0');
}
if(sign) return -s;
return s;
}
list* insert(list* head,char* coef,int expo)
{
list* node=(list*)malloc(sizeof(list));
if(node==NULL)
{
printf("Stack Overflow");
exit(1);
}
node->next=NULL;
node->coef=transform(coef);
node->expo=expo;
if(head==NULL) return node;
list* temp=head;
while(temp && temp->next)
temp=temp->next;
temp->next=node;
return head;
}
float power_of(float x,int expo)
{
if(expo==0) return 1;
int i=1;
float s=1;
if(expo > 0)
while(i++ <= expo)
s*=x;
else if (expo < 0)
while(i++ <= -expo)
s*=1.0/x;
return s;
}
float evaluate(list* head,float x)
{
if(head==NULL) return 0;
float s=0.0;
while(head)
{
s+=(head->coef)*power_of(x,head->expo);
head=head->next;
}
return s;
}
int main()
{
list* head=NULL;
char coef[11];
int expo,i=1;
float x;
printf("insert the polynome <type end to stop>:\n");
do
{
printf("insert the coefficient %d> : ",i);
scanf("%s",coef);
if(compare(coef,"end"))
{
printf("insert the exposnant %d> : ",i++);
scanf("%d",&expo);
head=insert(head,coef,expo);
}
}while(compare(coef,"end"));
printf("insert a value to evaluate the polynome : ");
scanf("%f",&x);
float value=evaluate(head,x);
printf("output : %f ",value);
return 0;
}
So I am making a tic tac toe game in C and I am having a problem where I am asking the user to undo their move by pressing 2. Each time it is their turn, they can either undo a move or continue to select there next turn by selecting another key.
It works how it should but I have a problem where if the user enters an alphabetical character, the program just repeatedly loops through saying that this is not a number when it checks my GetHumanMove function. Does anyone know how to make it stop doing this and just say this is not a number once without it looping the program?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <windows.h>
//Tic-Tac-Toe game in C
//20/03/2019
//5x5 Board with 4 in a row to win. Also has playable AI that randomly blocks human moves.
//Also has replay function using a doubly linked list
/*
int board[49] = {
;,;, ;, ;, ;, ;, ;,
;,1, 2, 3, 4, 5 ,;,
;,6, 7, 8, 9, 10,;,
;,11,12,13,14,15,;,
;,16,17,18,19,20,;,
;,21,22,23,24,25,;,
;,;, ;, ;, ;, ;, ;,
}
*/
struct node
{
int side;
int move;
int place;
struct node * prev;
struct node * next;
};
void append(struct node **, int, int, int);
void display(struct node *);
void delete(struct node **, int);
//Constants of pieces, border and empty places
enum { NOUGHTS, CROSSES, BORDER, EMPTY };
//Constants for human/computer win or draw
enum { HUMANWIN, COMPWIN, DRAW };
const int directions[4] = { 1, 7, 6, 8 };
int moveCount = 0;
//Values of original places to play
const int ConvertTo49[25] = {
8, 9, 10,11,12,
15,16,17,18,19,
22,23,24,25,26,
29,30,31,32,33,
36,37,38,39,40
};
void append(struct node ** list, int side, int move, int place)
{
struct node *temp , *current = *list;
if(*list == NULL)
{
*list = (struct node *) malloc(sizeof(struct node));
(*list) -> prev = NULL;
(*list) -> side = side;
(*list) -> move = move;
(*list) -> place = place;
(*list) -> next = NULL;
}
else
{
while(current -> next != NULL)
current = current -> next;
temp = (struct node *) malloc(sizeof(struct node));
temp -> side = side;
temp -> move = move;
temp -> place = place;
temp -> next = NULL;
temp -> prev = current;
current -> next = temp;
}
}
void delete(struct node ** list, int num)
{
struct node *temp = *list;
while(temp != NULL)
{
if(temp -> move == num)
{
if(temp == *list)
{
*list = (*list) -> next;
(*list) -> prev = NULL;
}
else
{
if(temp -> next == NULL)
temp -> prev -> next = NULL;
else
{
temp -> prev -> next = temp -> next;
temp -> next -> prev = temp -> prev;
}
free(temp);
}
return ;
}
temp = temp -> next;
}
printf("Element %d not found in the supplied list \n\n", num);
}
//Loop through a direction until a border square is hit
int GetNumForDir(int startSq, const int dir, const int *board, const int us)
{
int found = 0;
while(board[startSq] != BORDER)
{
if(board[startSq] != us)
{
break;
}
found++;
startSq += dir;
}
return found;
}
//Loop through directions and find four in a row
int FindFourInARow(const int *board, const int ourIndex, const int us)
{
int dirIndex = 0;
int dir = 0;
int countFour = 1;
for(dirIndex = 0; dirIndex < 4; ++dirIndex)
{
dir = directions[dirIndex];
countFour += GetNumForDir(ourIndex + dir, dir, board, us);
countFour += GetNumForDir(ourIndex + dir * -1, dir * -1, board, us);
if(countFour == 4)
{
break;
}
countFour = 1;
}
return countFour;
}
//Set up board structure
void InitialiseBoard(int *board)
{
//index variable
int index;
//set whole board to border squares initially
for(index = 0; index < 49; ++index)
{
board[index] = BORDER;
}
//Set up empty squares for placing pieces
for(index = 0; index < 25; ++index)
{
board[ConvertTo49[index]] = EMPTY;
}
}
//Print the board
void PrintBoard(const int *board)
{
//index variable
int index;
//Set pieces and places
char pceChars[] = "OX| ";
printf("\n\n\n");
//Loop through and only draw the actual playable squares, leaving out the border squares
for(index = 0; index < 25; ++index)
{
//Put lines inbetween places
if(index==1 || index==2 || index==3 || index==4 ||
index==6 || index==7 || index==8 || index==9 ||
index==11 || index==12 || index==13 || index==14 ||
index==16 || index==17 || index==18 || index==19 ||
index==21 || index==22 || index==23 || index==24)
{
printf(" |");
}
//Put space at start to space out board from edge of screen
if(index==0)
{
printf(" ");
}
//Print new line every 5 places
if(index!= 0 && index==5 || index==10 || index==15 || index==20)
{
printf("\n");
printf(" -------------------");
printf("\n");
printf(" ");
}
//Print each playable piece
printf(" %c", pceChars[board[ConvertTo49[index]]]);
}
printf("\n\n");
}
//Check if board has empty spaces
int HasEmpty(const int *board)
{
int index;
for(index = 0; index < 25; ++index)
{
if(board[ConvertTo49[index]] == EMPTY) return 1;
}
return 0;
}
//Function for making move of current player
void MakeMove(int *board, const int sq, const side)
{
//set board place that either player decides
board[sq] = side;
}
void UndoMove(int *board, int sq, int side)
{
//set board place that either player decides
board[sq] = side;
}
//Help the computer find a winning move
int GetWinningMove(int *board, const int side)
{
int ourMove = -1;
int winFound = 0;
int index = 0;
for(index = 0; index < 25; ++index)
{
if(board[ConvertTo49[index]] == EMPTY)
{
ourMove = ConvertTo49[index];
board[ourMove] = side;
if(FindFourInARow(board, ourMove, side) == 4)
{
winFound = 1;
}
board[ourMove] = EMPTY;
if(winFound == 1)
{
return ourMove;
}
ourMove = -1;
};
}
return ourMove;
}
//Get computer player move
int GetComputerMove(int *board, const int side)
{
int index;
int numFree = 0;
int availableMoves[25];
int randMove = 0;
//Set random number to randomly run a function
int randFunction = 0;
randFunction = (rand() % 2);
//Go for the winning move
randMove = GetWinningMove(board, side);
if(randMove != -1)
{
return randMove;
}
//If random function is 1, stop any winning move from the human
if(randFunction == 1)
{
randMove = GetWinningMove(board, side ^ 1);
if(randMove != -1)
{
return randMove;
}
}
randMove = 0;
//Loop through all squares and put piece in random place
for(index = 0; index < 25; ++index)
{
if(board[ConvertTo49[index]] == EMPTY)
{
availableMoves[numFree++] = ConvertTo49[index];
};
}
randMove = (rand() % numFree);
return availableMoves[randMove];
}
//Get human player move
int GetHumanMove(const int *board)
{
//Array for user input
int userInput;
char term;
//Start moveOK at 0
int moveOK = 0;
int move = -1;
//Loop through until move being made is valid
while(moveOK == 0)
{
printf("\n");
//Ask user for input of 1-9
printf("Please enter a place on the board to make your move, from 1 to 25: ");
//Make sure that user doesnt enter long string with number on the end that eventaully passes tests in the while loop
scanf("%d%c", &userInput, &term);
if(term != '\n')
{
move = -1;
printf("This is not a number\n");
continue;
}
//Check if input is in proper range
if(userInput < 1 || userInput > 25)
{
move = -1;
printf("Invalid Range\n");
continue;
}
//decrement move to get the array location of the playable places
userInput--;
//Check if place selected is already taken
if(board[ConvertTo49[userInput]] != EMPTY)
{
move = -1;
printf("Square not available\n");
continue;
}
//Set move ok to 1 after passing all the tests
moveOK = 1;
}
//Print move being made and return it
printf("\nHuman making Move at square: %d\n",(userInput+1));
return ConvertTo49[userInput];
}
//Run Game function
void RunGame()
{
struct node *list;
list = NULL;
//Display
printf("\n\n Noughts And Crosses Game:");
printf("\n =========================");
//game over variable
int gameOver = 0;
//Start on noughts side
int side = NOUGHTS;
//Record last move
int lastMoveMade = 0;
//Create new board
int board[49];
//Count of first move
int initialMove = 0;
//Initialise the Board
InitialiseBoard(&board[0]);
//Print the board to screen
PrintBoard(&board[0]);
//While game isn't over
while(!gameOver)
{
initialMove++;
//Human
if(side==NOUGHTS)
{
//Ask to undo move after first move played
if(initialMove > 1)
{
while(list -> prev != NULL)
list = list -> prev;
int undo;
printf("\n\nWould you like to undo your move? \nEnter 2 to undo or any other key/s to continue: ");
scanf("%d", &undo);
if( undo == 2)
{
while(list -> next != NULL)
list = list -> next;
char pceChars[] = "OX| ";
//printf(" %c", pceChars[board[ConvertTo49[index]]]);
int count = 2;
while(count != 0)
{
UndoMove(&board[0], list -> place, EMPTY);
list = list -> prev;
delete(&list, list -> next -> move);
moveCount--;
count--;
}
PrintBoard(&board[0]);
}
}
//Make new move for human
lastMoveMade = GetHumanMove(&board[0]);
MakeMove(&board[0], lastMoveMade, side);
moveCount++;
int humanMove;
//Find the position the computer is making on the 5x5 board
for(humanMove = 0; humanMove < 25; ++humanMove)
{
if(ConvertTo49[humanMove] == lastMoveMade)
{
break;
}
}
append(&list, 0, moveCount, lastMoveMade);
side = CROSSES;
}
//Computer
else
{
//Make move for computer
lastMoveMade = GetComputerMove(&board[0], side);
MakeMove(&board[0], lastMoveMade, side);
int compMove;
//Find the position the computer is making on the 5x5 board
for(compMove = 0; compMove < 25; ++compMove)
{
if(ConvertTo49[compMove] == lastMoveMade)
{
break;
}
}
printf("\nComputer making move at square: %d", compMove+1);
moveCount++;
append(&list, 1, moveCount, lastMoveMade);
side = NOUGHTS;
PrintBoard(&board[0]);
}
//If three in a row exists, game over
if(FindFourInARow(board, lastMoveMade, side ^ 1) == 4)
{
gameOver = 1;
if(side == NOUGHTS)
{
printf("\nGame Over!\n");
printf("Computer Wins! :(\n");
}
else
{
PrintBoard(&board[0]);
printf("\nGame Over!\n");
printf("Human Wins! :D\n");
}
}
//If no more moves, game is a draw
if(!HasEmpty(board))
{
PrintBoard(&board[0]);
printf("\n\nGame Over!\n");
gameOver = 1;
printf("It's a draw! :/\n");
}
}
/*
*
* Match Replay
*
*/
int answer;
printf("\n\nWould you like to replay the match? \nEnter 1 to replay or any other key/s to quit: ");
scanf("%d", &answer);
if(answer == 1)
{
InitialiseBoard(&board[0]);
while ( list != NULL )
{
MakeMove(&board[0], list -> place, list -> side);
PrintBoard(&board[0]);
char who[7];
if(list -> side == 0)
{
strcpy(who, "NOUGHTS");
//who = "NOUGHTS";
}
else
{
strcpy(who, "CROSSES");
//who = "CROSSES";
}
int moveMade;
//Find the position the computer is making on the 5x5 board
for(moveMade = 0; moveMade < 25; ++moveMade)
{
if(ConvertTo49[moveMade] == list -> place)
{
break;
}
}
printf ("\nMove:%2d Side:%8s Place: %d\n", list -> move, who, moveMade+1);
Sleep(2000);
list = list -> next ;
}
}
else
{
printf("\nGood Game! See ya!\n");
getch();
}
}
int main()
{
//Create random number
srand(time(NULL));
//Call Run Game to play
RunGame();
return 0;
}
Input that doesn't match your format doesn't get consumed by scanf. It remains in the input stream. So when you type a letter it fails to match the number you wanted %d and stays in the input stream.
scanf("%d%c", &userInput, &term);
Instead of scanf, it would be simpler to use getline to consume the entire line of input. And then parse the result with sscanf (the string-based version of the function) or another method.
char *line = NULL;
size_t len = 0;
while ((read = getline(&line, &len, stdin)) != -1) {
// Do something with line
int scanned = sscanf(line, "%d%c", &userInput);
if (scanned == EOF || scanned != 2) {
printf("Line failed to match\n");
}
}
Just read the manual page:
The format string consists of a sequence of directives which describe
how to process the sequence of input characters. If processing of a
directive fails, no further input is read, and scanf() returns. A
"failure" can be either of the following: input failure, meaning that
input characters were unavailable, or matching failure, meaning that
the input was inappropriate (see below).
You do not check the return value of scanf(). So you try to scan the same non-digit as digit all the time.
I want to find the distance between two nodes (number of node between them) in a circular linked list.
Where nodal is :
typedef struct node
{
int data;
struct node *next;
}nodal;
nodal *distance(nodal *start)
{
int n1,n2,d1=0,d2=0,c=0;
if(start==NULL)
{
printf("\nList is empty");
}
else
{
printf("\nEnter the fist node element : ");
scanf("%d",&n1);
printf("\nEnter the second node element : ");
scanf("%d",&n2);
nodal *ptr=start;
while(ptr->next!=start)
{
c++;
if(ptr->data==n1)
{
d1=c;
}
if(ptr->data==n2)
{
d2=c;
}
}
}
printf("The distance between two nodes is %d",(d2-d1));
return start;
}
I doesn't give any output.
Also suppose if circular list contains following data :
1,2,3,4,5,6,7,8,9
And if I give input
First node element as 9
Second node element as 4
Then this algorithm won't work.
Any suggestions for the change ?
Start counting when you find the first node and stop when you find the second one, something like:
int inc = 0, dist = 0;
if (n1 == n2) {
return 0;
}
node = start;
while (node) {
dist += inc;
if ((node->data == n1) || (node->data == n2)) {
if (inc++ == 1) return dist;
}
node = node->next;
if (node == start) break;
}
return 0;
First you have to go to the first element entered, in this process count will not be increased. Then start increasing to count until you reach the second element.
Code is below:
ptr=start;
while(ptr->data!=n1)
{
ptr=ptr->next;
}
//---now we have reached the first number----
while(ptr->data!=n2)
{
count++;
ptr=ptr->next;
}
There are multiple problems in your code:
the test for the end of the list prevents you from testing the last node.
you handle the case where n1 == n2 by returning 0, which may not be what is expected.
the distance between n1 and n2 will be negative if n2 appears before n1, which is incorrect: since the list is circular, if you keep scanning after n1, you will encounter n2 at a positive distance at most after wrapping over the first node.
Here is an alternate solution:
typedef struct node {
int data;
struct node *next;
} nodal;
nodal *distance(nodal *start) {
int n1, n2, d1 = 0, d2 = 0, length = 0;
if (start == NULL) {
printf("List is empty\n");
} else {
printf("\nEnter the fist node element : ");
if (scanf("%d", &n1) != 1) {
printf("invalid input\n");
return start;
}
printf("\nEnter the second node element : ");
if (scanf("%d", &n2) != 1) {
printf("invalid input\n");
return start;
}
nodal *ptr = start;
for (;;) {
length++;
if (ptr->data == n1 && !d1) {
d1 = length;
} else if (ptr->data == n2) {
if (d1) {
d2 = length;
break;
}
if (!d2)
d2 = length;
}
ptr = ptr->next;
if (ptr == start)
break;
}
}
if (d1 && d2) {
int dist = d2 - d1;
if (dist < 0)
dist += length;
printf("The distance between node(%d) and node(%d) is %d\n", d1, d2, dist);
} else {
if (d2)
printf("node(%d) not found\n", d1);
if (d1)
printf("node(%d) not found\n", d2);
}
return start;
}
I am trying to edit a program I made a year ago, but it seems I am failing somewhere because I can't get the result I want. I want to make the program to sort the numbers from low to high and the user should enter numbers until 0 is pressed. Would love ot get some help from someone advanced!
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add(struct node* p, int d)
{
struct node* q;
q = malloc(sizeof(struct node));
if (q == NULL)
printf("Not enaugh memory!");
else{
q->data = d;
if (List == NULL || List->data < d)
{
q->next = List;
List = q;
} else {
struct node *ptr = List;
while ((ptr->next != NULL) && (ptr->next->data>d)){
ptr = ptr->next;
}
q->next = ptr->next;
ptr->next = q;
}
}
}
int main()
{
int n, i, a;
printf("How many numbers are you going to enter? ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter a number: ");
scanf("%d", &a);
Add(List, a);
}
printf("\nEntered and sorted numbers are: ");
struct node *ptr = List;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
Just change to line
if (List == NULL || List->data < d)
to
if (List == NULL || List->data > d)
And change the line
while ((ptr->next != NULL) && (ptr->next->data>d)){
to
while ((ptr->next != NULL) && (ptr->next->data<d)){
And you have not added 0 check.Please add that, rest is fine. For this modify the for loop with this one
//printf("How many numbers are you going to enter? ");
//scanf("%d", &n);
for (;;)
{
printf("\nEnter a number: ");
scanf("%d", &a);
if(a == 0)
break;
Add(List, a);
}