Linked List Insert - c

I want to try insertion function for linked list. Function holds the record array and link array.for example;
head=0
string[0]="Angel" linked[0]=1
string[1]="Cesar" linked[1]=2
string[2]="Eduardo" linked[2]=3
string[3]="Pamela" linked[3]=-1/*-1 element does not show*/
head is Angel and Angel shows Eduardo.e.g. If you add element Denial,string[4]=Denial linked[4]=2 Denial shows Eduardo.Attention :---->>string[1]="Cesar" linked[1]=4 link array is updated.
I am getting some errors in this function.(element can not be added.) a little help
#define SIZE 10
int main()
{
int linked[SIZE]={3,0,4,-1,1};
char *str[]={"Ellian","Calanthe","Adela","Gardenia","Barbara",NULL};
return 0;
}
void list(int arr[],int head,int linky[]){
int adr=head;
while(adr!=-1){
puts(arr[adr]);
adr=linky[adr];
}
}
void insert(int arrr[],int head,int linky[],char element){
int k,N=0,prev,next;
for(k=0;arrr[k]<NULL;k++)
N++;
arrr[N]=element;
if(element>arrr[head])
{
prev=head;
next=linky[head];
while((next!=-1) && (arrr[next]<element)){
prev=next;
next=linky[next];
}
linky[prev]=N;
linky[N]=next;
}
else{
linky=head;
head=N;
}
N++;
listele(arr,N,linky);
}

replace
#define SIZE 10
by
int size = 10;
and replace
void insert(char str[],int link[],int size,int first)
by
void insert(char str[],int link[],int& size,int& first)
to start of. Still might not work but atleast now the things you do actually do what you want them to do

You are using your stringarray contents before initializing them, to avoid undefined behaviour change this:
char string[SIZE];
to this:
char string[SIZE] = {0};
If you want your string array to start with zeroes inside.
Also notice you are running past the last element of your arrays when you do:
link[size] = ...
as you array is of exactly size elements then the max index you can use is size - 1.

Related

C | Pointer doesnt give the value

Im trying to do something easy, but i could find any solution.
I have an array, and I want to find an index, and update the pointer from a Function,
When Im trying to return the **Address of the index, and after it Print the Value at that index, I get nothing..
I hope you can Help me
int main()
{
int array[]={3,2,3,4};
int* pointer=NULL;
doIT((int *)array,4,pointer);
printf(" value of address %d",*pointer);
}
void doIT(int *p,int sizes,int** pointer){
for(int i =0;i<sizes;i++)
{
if(*p==4)
{
printf("TT %d",*p);
pointer=&p;
// printf("\n %d \n",pointer);
}
p++;
}
}
There are two errors: First, you have to call the function with
&pointer
and second, in the function body you have to set
*pointer=p;

i am trying to add integers in my list in ascendant order!!any help pleasee?

i am trying to make a list that order integers in ascendant order during the insertation phase ,for some reason it gives me a wierd number after putting the list in the right order,can someone tell me where i messed up?or if you have any optimal version of this functionajout_liste_croissant()?
#include"liste.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void ajout_liste_croissant(element**l,int info)
{assert(*l);
element*nouv;
nouv=(element*)malloc(sizeof(element));
if(vide(*l))/*if list is empty will add the new info without comparing */
{
*l=nouv;
(*l)->cle=info;
(*l)->suivant=NULL;}
else
{element*courant,*q;
int inter;
courant=*l;
int trouve=0;
while(courant!=NULL&&!trouve)/*parcouring the list till the end or when finding a value bigger than the entered one*/
{if(info<courant->cle)
trouve=1;
else{q=courant;/*this pointer get the adress of the previous current position in the list*/
courant=courant->suivant;}}/*the current pointer move to next adress*/
if(trouve)
{inter=courant->cle;
courant->cle=info;/*exchanging values in case current positon is bigger than the entered value*/
info=inter;
nouv->cle=info;
nouv->suivant=courant->suivant;
courant->suivant=nouv;
}
else
/*if the list reaches end*/
{
nouv->cle=info;
q->suivant=nouv;/*adding the new element at the end of the list*/
nouv->suivant=NULL;}
}
}
void afficher(element*l)
{assert(!vide(l));
while(l!=NULL)
{printf("%d\n",l->cle);
l=l->suivant;}
}
There are not too many errors. But your code is absolutely unreadable. I do not know how you could read it and, therefore, debug it.
So, I added spaces, indentations, new lines ... and it works with minor changes. I let you discover these changes. This answer is not necessarily the best way to do it but, starting from your code, I tried to do the minimum of changes. Moreover, avoid French (text, function names, ...) in your code when you ask question on stackoverflow.
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct element {
int cle;
struct element *suivant;
} element;
void creer_liste(element **l) {
assert(l);
*l=NULL;
}
int vide(element *l) {
return(l==NULL);
}
void ajout_liste_croissant(element **l,int info) {
assert(l);
element *nouv;
nouv=(element*)malloc(sizeof(element));
if( vide(*l) ) {
*l=nouv;
(*l)->cle=info;
(*l)->suivant=NULL;
} else {
element *courant,*q;
int inter;
courant=*l;
int trouve=0;
while ( courant != NULL && !trouve ) {
if(info<courant->cle)
trouve=1;
else {
q=courant;
courant=courant->suivant;
}
}
if(trouve) {
inter=courant->cle;
courant->cle=info;
info=inter;
nouv->cle=info;
nouv->suivant=courant->suivant;
courant->suivant=nouv;
} else {
nouv->cle=info;
q->suivant=nouv;
nouv->suivant=NULL;
}
}
}
void afficher(element *l) {
assert(!vide(l));
while(l!=NULL) {
printf("%d\n",l->cle);
l=l->suivant;
}
}
int main() {
element *data;
int nb,info;
creer_liste(&data);
printf("donner la taille de la liste:\n");
scanf("%d",&nb);
for(int i=0;i<nb;i++) {
printf("donner un entier:\n");
scanf("%d",&info);
ajout_liste_croissant(&data,info);
}
printf("_____________________\n");
afficher(data);
}

Linked list sort from smallest to biggest

I am trying sort a number in a linked list from small to big.
But its not working !
the debugger says there are a problem when i put the second number into the
list ( in main )but i dont know why .
Any help ?
#include<stdio.h>
#include<stdlib.h>
typedef struct list list;
struct list{
int a;
list *nxt;
};
void sort(list *l){
int temp,tp;
list *AIDE,*k;
k=AIDE=(list*)malloc(sizeof(list));
while (l->nxt!= NULL)
{
while (l->nxt->a < l->a)
{
temp=l->a;
l=l->nxt;
l->nxt->a=temp;
l=l->nxt;
while (l->a < AIDE->nxt->a )
{
tp=AIDE->a;
AIDE->a=l->a;
AIDE->nxt->a=tp;
AIDE=AIDE->nxt;
}
}
l=l->nxt;
}
while (k->nxt!= NULL)
{
l->a=k->a;
l=l->nxt;
k=k->nxt;
}
l->nxt=NULL;
}
int main() {
list *t,*s;
int n,i,c=0;
printf("\n how many number you need to enter? ");
scanf("%d",&n);
s=t=(list*)malloc(sizeof(list)*n);
while (c!=n)
{
printf("\n Donner le nb %d :",c+1);
scanf("%d",&t->a);
t=t->nxt;
c++;
}
t->nxt=NULL;
sort(s);
while (t->nxt!=NULL)
{
printf("%d",t->a);
}
return 0;
}
In the loop where you have the problem, what do you think the expression t=t->nxt would do?
When you enter the loop, t is pointing to allocated but uninitialized memory, therefore dereferencing e.g. t->nxt will lead to undefined behavior.
A simple solution would be to e.g. do
t->nxt = t++ + 1;

Unable to create Adjacency List for an undirected Graph using C

I'm faced with a problem which I've been unable to tackle for quite some time.
I've been given a graph as follows,in a M x N matrix:
2 2
a b
a c
Note
I've interpreted the graph above as a matrix,only consisting of non-diagonal edges.
Here the first line represents values of M and N respectively.
The graph is only connected either along vertical,or adjacent direction,i.e.,up,down,left and right. diagonal edges not present.
In order to find the adjacency list of the graph(the desired output here):
a-b-c
b-a-c
c-a-b
Steps followed by me in the code:
1.Read M x N matrix into a 2D array.
2.Created a list of unique vertices of the graph as Unode[arrmax].
3.For each element of the matrix,if the character matches with an element of the unique vertices list,I've called the modify Adjacency List procedure that searches the neighbours of the concerned matrix vertex and populates/appends to the the Adjacency list if distinct nodes are found.
It takes as arguments, i,j,M,N,AdjList,number of elements in the list and makes the changes.
5.I've kept the list of nodes to be global for easy modification.
6.Next I intend to use the adjacency list produced to use in DFS procedure and find the DFS forest.
The Problem statement:
the input consists of a grid of size M X N. Each cell in the grid
contain a lower case letter of the English alphabet.In a natural way,
the cells are of two types: boundary cells and internal cells. Each
internal cell in the grid has four neighbours in one of the left,
right, top, down directions. A string of characters can be formed by
starting at any cell and traversing the grid through the neighbours.
You have to print all the possible strings subject to the following
constraints:
**No two characters in a string can be same
**No two strings can be same in the final output
**The strings should be printed in alphabetically sorted order.
INPUT:
First line contains two integers M and N
Next M lines contains N space separated characters each
OUTPUT:
Print all possible strings in sorted order and obeying the above constraints.
INPUT SIZE:
1 <= M, N <= 20
SAMPLE INPUT:
2 2
a b
a c
SAMPLE OUTPUT:
a ab abc ac acb b ba bc bca c ca cb cba
[UPDATE]:
Completely redesigned the code,used structures for the graph nodes,and one for handling indices.
Yet the result I'm getting:
a--b-a
b--a
a
c--a
My code[Relevant Portion]:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#define ADJMAX 20
#define arrmax 400
typedef struct uniq_node{
char ch;
char AdjList[ADJMAX];
int numofelem;
int visited;
}unode;
unode Ulist[arrmax];
int uniq_tot=0;
typedef struct index
{
int i,j;
}Ind;
Ind indx;
int charcomp(char sch,char arr[],int arrlim);
void adjModify(unode*,char*,int,int,Ind);
int chIndex(int,int,int,int);
int main(void) {
int mvar,nvar;
char str[15],*token;
long integer;
/*To scan the values of M & N*/
scanf("%d %d\n",&mvar,&nvar);
int iter,iterv,jterv;
/*To create the character matrix of M x N*/
char cmat[mvar][nvar];
/*Initializing the unique nodes list*/
/*To read-in the matrix from the stdin:-A LOT OF HARD WORK*/
for(iterv=0;iterv<mvar;iterv++)
{
fgets(str,50,stdin);
jterv=0;
token=strtok(str," ");
while(token)
{
/*Assigning value to the character matrix*/
cmat[iterv][jterv]=*token;
/*Code to populate the list of unique elements*/
if(charcomp(*token,Ulist[uniq_tot].AdjList,uniq_tot)==3)
{
Ulist[uniq_tot].ch=*token;
uniq_tot++;
Ulist[uniq_tot].numofelem=1;
Ulist[uniq_tot].AdjList[0]=*token;
//Ulist[uniq_tot].visited=0;
}
jterv++;
token = strtok(NULL, " ");
}
}
/*To populate the adjacency lists */
char ch;
for(iterv=0;iterv<mvar;iterv++)
{
for(jterv=0;jterv<nvar;jterv++)
{
ch=cmat[iterv][jterv];
indx.i=iterv;
indx.j=jterv;
for(iter=0;iter<uniq_tot;iter++)
{
if(ch==Ulist[iter].ch)
break;
}
adjModify(&Ulist[iter],(char*)cmat,mvar,nvar,indx);
}
}
/*for(iter=0;iter<uniq_tot;iter++)
{
printf("%c",Ulist[iter].ch);
printf("\n%s\n",Ulist[iter].AdjList);
for(iterv=0;iterv<Ulist[iter].numofelem;iterv++)
{
printf("-%c",Ulist[iter].AdjList[iterv]);
}
printf("\n");
}*/
return 0;
}
int chIndex(int i,int j,int mvar,int nvar)
{
return (i>=0 && i<mvar && j>=0 && j<nvar);
}
void adjModify(unode* Unode,char* mat,int mvar,int nvar,Ind mind)
{
int idum,jdum;
if(chIndex(mind.i,mind.j-1,mvar,nvar))
{
idum=mind.i;
jdum=mind.j-1;
if(charcomp(*(mat+idum*nvar+jdum),Unode->AdjList,Unode->numofelem)==3)
{
++Unode->numofelem;
Unode->AdjList[Unode->numofelem]=*(mat+idum*nvar+jdum);
printf("\nI'm here in coord:(%d,%d), with element: %c, and AdjList: %s for character: %c",idum,jdum,*(mat+idum*nvar+jdum),Unode->AdjList,Unode->ch);
}
}
if(chIndex(mind.i,mind.j+1,mvar,nvar))
{
idum=mind.i;
jdum=mind.j+1;
if(charcomp(*(mat+idum*nvar+jdum),Unode->AdjList,Unode->numofelem)==3)
{
++Unode->numofelem;
Unode->AdjList[Unode->numofelem]=*(mat+idum*nvar+jdum);
printf("\nI'm here in coord:(%d,%d), with element: %c, and AdjList: %s for character: %c",idum,jdum,*(mat+idum*nvar+jdum),Unode->AdjList,Unode->ch);
}
}
if(chIndex(mind.i-1,mind.j,mvar,nvar))
{
idum=mind.i-1;
jdum=mind.j;
if(charcomp(*(mat+idum*nvar+jdum),Unode->AdjList,Unode->numofelem)==3)
{
++Unode->numofelem;
Unode->AdjList[Unode->numofelem]=*(mat+idum*nvar+jdum);
printf("\nI'm here in coord:(%d,%d), with element: %c, and AdjList: %s for character: %c",idum,jdum,*(mat+idum*nvar+jdum),Unode->AdjList,Unode->ch);
}
}
if(chIndex(mind.i+1,mind.j,mvar,nvar))
{
idum=mind.i+1;
jdum=mind.j;
if(charcomp(*(mat+idum*nvar+jdum),Unode->AdjList,Unode->numofelem)==3)
{
++Unode->numofelem;
Unode->AdjList[Unode->numofelem]=*(mat+idum*nvar+jdum);
printf("\nI'm here in coord:(%d,%d), with element: %c, and AdjList: %s for character: %c",idum,jdum,*(mat+idum*nvar+jdum),Unode->AdjList,Unode->ch);
}
}
}
/*Comparison routine*/
int charcomp(char fchar,char arr[],int ucindex)
{
int ivar;
for(ivar=0;ivar<ucindex;ivar++)
{
if(arr[ivar]==fchar)
return;
}
return 3;
}
I think you can skip creating individual nodes for every element in the 2D array. Having the 2D array implies a structured connectivity. When it starts getting large, traversing all these elements may become cumbersome.
My recommended approach would be the following:
Scan of the matrix and pull unique nodes. i.e. start with a scan and have the simple list a,b,c (you'll need to sort them).
Create a struct for each unique node consisting the number of paths you currently have and an array of char arrays to store each one in. i.e. char** myArray={{a},{ab},{abc},{ac},{acb}} would be the one for a (This is of course unknown when you start).
Loop through your unique nodes, and one by one find the location in the 2D array. Don't save them, just go through them one by one and do a scan function to look for all their paths.
The scan function should be recursive so it can go as far as it needs to while checking every possible path (recursive will help you check every direction at every node you traverse). Keep track of where you've been, and at ever step check that you have not already encountered that character.
When you can't go any further, make sure the string has not already been included, if it has continue to the next path, if not add it to the list.
this is my code in c++ without any library that can work in c but you just have to use in c printf instead of cout and instead of class use struct that's all. I also write code for breadth first traversal see below.
and include the header file also
// #include <stdio.h>
//#include<stdlib.h>
#include<iostream
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data=data;
this->next=NULL;
// cout<<"from node file"<<endl;
}
};
class Queue {
Node * head;
Node * tail;
int length;
public:
Queue() {
head=NULL;
tail=NULL;
length=0;
}
bool isEmpty() {
return length==0;
}
int size() {
return length;
}
int front() {
if(head==NULL) {
cout<<"Empty Queue"<<endl;
return 0;
}
return head->data;
}
void enqueue(int element) {
Node * newNode =new Node(element);
if(head==NULL) {
head=newNode;
tail=newNode;
}else{
tail->next=newNode;
tail=newNode;
}
length++;
}
int dequeue() {
if(head==NULL) {
cout<<"Empty queue"<<endl;
return 0;
}
int output= head->data;
Node * temp=head;
head=head->next;
temp->next=NULL;
delete temp;
length--;
return output;
}
};
class AdjList{
public:
Node * head;
AdjList() {
head=NULL;
//cout<<"from adlist"<<endl;
}
void add (int data) {
Node * newNode=new Node(data);
if(head==NULL) {
head=newNode;
}else {
Node* temp=head;
while(temp->next!=NULL) {
temp=temp->next;
}
temp->next=newNode;
}
}
};
class Graph{
public:
int v;
AdjList* adjList;
Graph(int v) {
this->v=v;
adjList=new AdjList[v];
}
void addEdge(int src, int dest) {
adjList[src].add(dest);
///for bidrectional add below code
//adjList[dest].add(src);
}
void print(){
for(int i=0;i<v;i++){
Node *temp = adjList[i].head;
cout << i << " -> ";
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
void bfs(int src) {
// using a queue also in this file how to add queue structure
Queue q;
bool* visited=new bool [v]{0};
q.enqueue(src);
visited[src]=true;
while(!q.isEmpty()) {
int node= q.front();
cout<<node<<" ";
q.dequeue();
Node *temp = adjList[node].head;
while(temp!=NULL){
if(!visited[temp->data]) {
q.enqueue(temp->data);
visited[temp->data]=true;
}
// cout<<"data "<<temp->data;
temp=temp->next;
/// how to traverse
}
}
}
};
int main(){
Graph g(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3,4);
g.addEdge(4,5);
g.bfs(0);
// g.print();
return 0;
}

How to use two parameters pointing to the same structure in one function?

I have my code below that consits of a structure, a main, and a function. The function is supposed to display two parameters that have certain values, both of which point to the same structure.
The problem I dont know how to add the SECOND parameter onto the following code :
#include<stdio.h>
#define first 500
#define sec 500
struct trial{
int f;
int r;
float what[first][sec];
};
int trialtest(trial *test);
main(){
trial test;
trialtest(&test);
}
int trialtest(trial *test){
int z,x,i;
for(i=0;i<5;i++){
printf("%f,(*test).what[z][x]);
}
return 0;
}
I need to add a new parameter test_2 there (IN THE SAME FUNCTION) using this code :
for(i=0;i<5;i++){
printf("%f,(*test_2).what[z][x]);
How does int trialtest(trial *test) changes ?
and how does it change in main ?
I know that I should declare test_2 as well, like this :
trial test,test_2;
But what about passing the address in the function ? I do not need to edit it right ?
trialtest(&test); --- This will remain the same ?
So please, tell me how would I use test_2 as a parameter pointing to the same structure as test, both in the same function..
Thank you !!
Please tell me if you need more clarification
I think that this is your homework, so I'll just write a different function that may give you an idea of what (I think) you need to do. I read that you don't want to change the trail_test parameter list, so I stuck with a similar parameter list.
struct thing {
/* put some stuff here */
};
typedef struct thing thing; /* because this is C, not C++ */
int how_many_things(thing * thing_list);
int main(void) {
int i;
thing * a;
int count_init = random(); /* let's surprise ourselves and make a random number of these */
count_init %= 128; /* but not too many or it might not work at all */
a = malloc(count_init*sizeof(things)+1);
for (i = 0; i < count_init; i++) {
thing_init(&(a[i]));
}
make_illegal_thing(&(a[count_init]) ); /* like '\0' at the end of a string */
printf("There are %i things in the list\n", how_many_things(a) );
return 0;
}
/* This is very similar to strlen */
int how_many_things(thing * a) {
int count = 0;
while (is_legal_thing(a) ) {
a++;
count++;
}
return count;
}

Resources