I wrote a program that has many functionalities but I can not swap 2 elements of 2 nodes in the linked list.Actually I can swap 2 nodes by changing their links but I can not swap 2 elements when the user requested 2 elements swapping.Here is my code without any swap operation.Again I have to say I want to do this swap operation by swapping 2 node elements not changing node links.How can I get rid of this problem?Any help will be appreciated.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
typedef struct node nodetype;
void insert(int ,struct node **);
void display(struct node *);
void search(int, struct node *);
void delete(int, struct node **);
int main(void){
nodetype *p;
p=NULL;
int x=0,choice;
int s_no,k,r_no;
while(x!=1){
printf("enter 1 for insert\n");
printf("enter 2 for display\n");
printf("enter 3 for search\n");
printf("enter 4 for delete\n");
printf("enter 0 for exit\n");
fflush(stdout);
scanf("%d",&choice);
if(choice==1){
printf("enter inserted no\n");
fflush(stdout);
scanf("%d",&k);
insert(k,&p);
}
else if(choice==2)
display(p);
else if(choice==3){
printf("enter searched no\n");
scanf("%d",&s_no);
search(s_no, p);
}
else if(choice==4){
printf("enter deleted no\n");
scanf("%d",&r_no);
delete(r_no,&p);
}
else
printf("invalid choice\n");
}
return 0;
}
void display ( struct node *p)
{
printf("the content is:\n");
if(p==NULL)
printf("the link is empty\n");
while ( p != NULL )
{
printf ( "%d ", p -> data ) ;
p = p -> next ;
}
printf ( "\n" ) ;
}
void search(int no, struct node *p){
nodetype * loc;
for(loc=p;loc!=NULL;loc=loc->next)
{
if(no==loc->data){
printf("\nthe number exist in the list\n");
return;
}
}
printf("\nthe number is not exist in the \n");
}
void insert(int x,struct node **p)
{
struct node *r,*temp=*p;
r = (struct node *)malloc ( sizeof (struct node)) ;
r ->data = x ;
r->next=NULL;
if ( *p == NULL)
{
*p = r ;
}
else
{
while(temp->next!= NULL)
{
temp=temp->next;
}
temp->next=r;
}
}
void delete(int num, struct node **p){
struct node *temp,*x;
temp=*p;
x= NULL;
while (temp->next !=NULL){
if(temp->data == num)
{
if (x==NULL)
{
*p = temp->next;
free(temp);
return;
}
else
{
x->next = temp->next;
free(temp);
return;
}
}
x=temp;
temp=temp->next;
}
printf(" No such entry to delete ");
}
I attempted swap operation with using
user entered numbers.For instance,the
user entered 12 and 45 in order to
swap in the linkedlist.How can I do
that?
I would suggest you extend the existing function with return values, (not tested just the idea)
nodetype * search(int no, struct node *p){
nodetype * loc;
for(loc=p;loc!=NULL;loc=loc->next)
{
if(no==loc->data){
printf("\nthe number exist in the list\n");
return loc;
}
}
printf("\nthe number is not exist in the \n");
return NULL;
}
After that you call search for both values entered by the user.
Then you swap the values in place without changing any pointer references simply be assigning new values. Of course you need to check whether the nodes were actually found (not NULL).
nodetype *node1;
nodetype *node2;
node1 = search( userInput1, &p );
node2 = search( userInput2, &p );
int tmp_data = node1->data;
node1->data = node2->data;
node2->data = tmp;
Related
I've been trying to get this search function work but it says element not found even when the element is in the tree. Every other function works.
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *lchild;
int info;
struct node *rchild;
};
int flag;
struct node *root = NULL;
struct node *insert(struct node *ptr, int ikey);
void in_order_search(struct node *ptr, int val);
void display(struct node *ptr,int level);
int main( )
{
struct node *root=NULL,*ptr;
int choice,k,v;
while(1)
{
printf("\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Search\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the key to be inserted : ");
scanf("%d",&k);
root = insert(root, k);
break;
case 2:
printf("\n");
display(root,0);
printf("\n");
break;
case 3:
printf("\nEnter the key to be searched : ");
scanf("%d",&v);
in_order_search(root, v);
if (flag==1)
{
printf("Element present in the binary tree\n");
}
else
{
printf("Element not present in the binary tree\n");
}
break;
default:
exit(1);
}
}
return 0;
}
struct node *insert(struct node *ptr, int ikey )
{
if(ptr==NULL)
{
ptr = (struct node *) malloc(sizeof(struct node));
ptr->info = ikey;
ptr->lchild = NULL;
ptr->rchild = NULL;
}
else if(ikey < ptr->info) /*Insertion in left subtree*/
ptr->lchild = insert(ptr->lchild, ikey);
else if(ikey > ptr->info) /*Insertion in right subtree */
ptr->rchild = insert(ptr->rchild, ikey);
else
printf("\nDuplicate key\n");
return ptr;
}
void in_order_search(struct node *ptr, int val)
{
if (!ptr)
{
return;
}
in_order_search(ptr->lchild, val);
if(ptr->lchild == val)
{
printf("\nElement present in the binary tree.\n");
flag = 1;
}
in_order_search(ptr->rchild, val);
}
void display(struct node *ptr,int level)
{
int i;
if(ptr == NULL )
return;
else
{
display(ptr->rchild, level+1);
printf("\n");
for (i=0; i<level; i++)
printf(" ");
printf("%d", ptr->info);
display(ptr->lchild, level+1);
}
}
6 8 7 9 3 4 2
This is the tree I enter and I search for all of the elements in that but it still says element not present in the binary tree. I've been trying to integrate this search function to another code I found on the internet so forgive me if it looks messy. And I'm a beginner as well so if I'm not sure if it's a silly mistake or not.
this is the changes i have made and its works:
void in_order_search(struct node *ptr, int val)
{
if (!ptr)
{
return;
}
in_order_search(ptr->lchild, val);
if(ptr->info == val)
{
/* printf("\nElement present in the binary tree.\n"); to prevent double printing
*/ flag = 1;
return;/* no need to go to the next line*/
}
in_order_search(ptr->rchild, val);
}
also, pay attention to the line caused seg fault:
ptr->lchild == val
this is the bad line
if(ptr->info == val)
this is the correction
I have to write a program, whitch will show out graph results in the form of an adjacency list and adjacency matrix. I've guided myself by a tutorial on YT on how to implement the adjency list, and with the current stored data (whitch the user is introducing himself, like the number of nodes, edges, to how many edges a edge is connected and to which one) and I want to know/understand how, with the already stored data, to build a adjacency matrix.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void read_graf(struct node *ad[], int no_of_nodes);
void print_graf(struct node *ad[], int no_of_nodes);
int main()
{
int op;
int i,j,k, nodes;
begin:
printf("Type in the number of edges: ");
scanf("%d", &nodes);
struct node *adj[nodes];
for (i=0;i<nodes;i++)
adj[i] = NULL;
read_graf(adj,nodes);
print_graf(adj,nodes);
printf("\nDo you want to try again? 1 for yes and 0 for no: ");
scanf("%d", &op);
if (op==1)
goto begin;
else
{
printf("Thank you for visiting! :)");
exit(0);
}
return 0;
}
void read_graf(struct node *ad[], int no_of_nodes)
{
struct node *new_node;
int i,j,k, val;
for (i=0;i<no_of_nodes;i++)
{
struct node *last= NULL;
printf("\n To how many edges is edge %d connected to: ", i+1);
scanf("%d", &k);
for (j=0;j<k;j++)
{
printf("To which edges is it connected : ");
scanf("%d", &val);
new_node = (struct node *)malloc(sizeof(struct node*));
new_node->data = val;
new_node->next = NULL;
if(ad[i]==NULL)
ad[i]= new_node;
else
last->next = new_node;
last = new_node;
}
}
}
void print_graf(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
int i,j;
for(i=0;i<no_of_nodes;i++)
{
ptr = ad[i];
printf("\n x%d : ", i+1);
while(ptr != NULL)
{
printf("%d,\t", ptr->data);
ptr = ptr->next;
}
printf("0");
}
}
If you only need to print out the adjacency matrix and assuming that a 1 would represent a connection between node i and node j, you just have to slightly modify the inner loop inside the print_graf function.
void print_as_mat(struct node *ad[], int no_of_nodes)
{
struct node *ptr = NULL;
for(int i = 0; i < no_of_nodes; ++i)
{
ptr = ad[i];
// Loop over all the possible nodes
for(int j = 0; j < no_of_nodes; ++j)
{
if ( ptr && ptr->data == j ) {
// ^^^^^^^^^^^^^^ Check if the index correspond to the
// current node in the adjacency list.
printf(" 1");
// update the current node in the list, but only here.
ptr = ptr->next;
}
else {
printf(" 0");
}
}
// The row is completed.
putchar('\n');
}
}
As a practice for final exam, I am practicing a linked list. But now I am stuck at printing input data on my code. I made this linked list and want to print input data. But my code does not print anything.
What's wrong with my code?
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int a,b ;
struct Node* next;
}NODE;
void makenode()
{
int a;
int b;
printf("enter the name : ");
scanf("%d",&a);
printf("enter the sur name : ");
scanf("%d",&b);
NODE* node1=malloc(sizeof(NODE));
node1->a=a;
node1->b=b;
node1->next=NULL;
return node1;
}
void printList()
{
NODE *ptr=NULL;
while(ptr!=NULL){
printf("%d", ptr->a);
printf("%d", ptr->b);
ptr = ptr->next;
}
}
int main()
{
NODE *head = malloc(sizeof(NODE));
head->next=NULL;
makenode();
printList();
return 0;
}
makenode() return type is void, it should be NODE*.
printList() does not fech the list so it can't know what to print, moreover ptr is NULL so it never enters the print loop.
Fixed code with comments:
Live demo
#include <stdlib.h>
#include <stdio.h>
typedef struct Node {
int a, b;
struct Node *next;
} NODE;
NODE* makenode() { //return type NODE*
NODE *node1 = malloc(sizeof(*node1));
printf("enter the name : ");
scanf("%d", &node1->a);
printf("enter the sur name : ");
scanf("%d", &node1->b);
node1->next = NULL;
return node1;
}
void printList(const NODE *ptr) { //pass NODE* ptr as an argument
int i = 1;
while (ptr != NULL) {
printf("Node %d\n", i++);
printf("a: %d\n", ptr->a);
printf("b: %d\n", ptr->b);
ptr = ptr->next;
}
}
int main() {
//make first node
NODE *head = makenode(); //assing node
// add one more node
NODE* node = makenode();
head->next = node; //chain second node
printList(head); //print nodes
return EXIT_SUCCESS;
}
On another note:
It's kind of strange that the names are int and not strings.
You could do:
Live demo
typedef struct Node {
char name[100]; //names as strings
char surname[100];
struct Node *next;
} NODE;
NODE* makenode() { //return type NODE*
NODE *node1 = malloc(sizeof(*node1));
printf("enter the name : ");
scanf(" %99[^\n]", node1->name);
printf("enter the sur name : ");
scanf(" %99[^\n]", node1->surname);
node1->next = NULL;
return node1;
}
void printList(const NODE *ptr) { //pass NODE* ptr as an argument
int i = 1;
while (ptr != NULL) {
printf("Node %d\n", i++);
printf("Name: %s\n", ptr->name);
printf("Surname: %s\n", ptr->surname);
ptr = ptr->next;
}
}
//...
//main is the same
here is a program which inserting 2 names 2 paths and 2 duration s into linked list (struct of linked lists) , printing them and swapping between them when the duration of the first node is 8.
but when the program printing the nodes its prints from all of the nodes the name and the path of the last node
please help me
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Frame
{
char *name;
unsigned int duration;
char *path; // may change to FILE*
}*n3;
typedef struct Frame frame_t;
struct Link
{
frame_t *frame;
struct Link *next;
}*n ;
typedef struct Link link_t;
struct Link* insert(struct Link *n3);
void print(struct Link* head, int flag);
void swap(struct Link **head, int value);
#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
int main()
{
struct Link* head = NULL;
int flag = 0;
int num = 0;
char namearray[MAX_NAME_SIZE] = { 0 };
char patharray[MAX_PATH_SIZE] = { 0 };
printf("1\n");
printf("\n");
for (int i = 0; i < 2; i++)
{
printf("Enter a number you want to insert - ");
scanf("%d", &num);
printf("\nEnter the name - ");
scanf("%s", &namearray);
printf("\nEnter the path - ");
scanf("%s", &patharray);
printf("\n");
head = insert(head,num,namearray,patharray);
}
print(head, flag);
swap(&head, 8);
printf("1\n");
system("pause");
return 0;
}
struct Link *insert(struct Link *p, int n, char namearray[MAX_NAME_SIZE], char patharray[MAX_PATH_SIZE]) //insert func
{
struct node *temp;
if (p == NULL) //if the node is empty
{
p = (struct Link *)malloc(sizeof(struct Link)); //gives memory to the node
p->frame = (struct Frame *)malloc(sizeof(struct Frame));
if (p == NULL)
{
printf("Error\n");
}
else
{
printf("The number added to the end of the list\n");
}
p->frame->duration = n; //its runing untill the node item is NULL
p->frame->name = namearray;
p->frame->path = patharray;
p->next = NULL;
}
else
{
p->next = insert(p->next, n , namearray , patharray);/* the while loop replaced by
recursive call */
}
return (p);
}
void print(struct Link* head , int flag)//print func
{
if (head == NULL && flag == 0) //if the node is empty
{
printf("The list is empty\n");
return 1;
}
if (head == NULL && flag != 0) //if the node isnt empty but we are in the NULL (last) item of the node
{
printf("\n");
printf("the nodes of the list printed\n");
return;
}
printf("%d ", head->frame->duration);//prints the currect item
printf("\n");
printf("%s ", head->frame->name);//prints the currect item
printf("\n");
printf("%s ", head->frame->path);//prints the currect item
printf("\n");
print(head->next, ++flag);//calls the func recursevly
return 1;
}
void swap(struct Link **head, int value)
{
while (*head && (*head)->frame->duration != value)
{
head = (*head)->next;
}
if (*head && (*head)->next)
{
struct list *next = (*head)->next->next;
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = next;
}
}
here is the print :
the print of the program
I am working on a program that inserts into a linked-list in sorted order, but it keeps seg faulting, and I can't figure out why. I suspect it has something to do with the pointers, but I can't tell as these are still a little bit confusing to me at this point in my programming career. Also, I must keep the insert prototype the same. I can't change the node parameter into a double pointer. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct node {
int data;
struct node *next;
};
int main ()
{
struct node* first;
int temp,x,y;
struct node *create (struct node *first);
first = NULL;
void display (struct node *first);
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter Element: ");
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(first,x);
y--;
}
printf ("\nThe list after creation is: ");
display (first);
printf ("\nThe sorted list is: ");
display (first);
return(0);
} /*END OF MAIN*/
insert_sorted_linked_list(struct node* head, int val)
{
struct node* pCur;
struct node* pNew = (struct node*) (malloc(sizeof(struct node)));
pNew -> data = val;
pNew ->next = NULL;
pCur = head;
if( pCur->data == NULL )
{
head->data = pNew->data;
head->next = NULL;
}
else if (pNew->data < pCur->data)
{
pNew ->next = pCur ;
head = pNew;
}
}
void display (struct node *first)
{ struct node *save; /*OR sort *save */
if (first == NULL)
printf ("\nList is empty");
else
{ save = first;
while (save != NULL)
{ printf ("-> %d ", save->data);
save = save->next;
}
getch();
}
return;
}
EDIT: Changed main to int. The debugger doesn't like the lines:
struct node* pNew = (struct node*) (malloc(sizeof(struct node)));
if( pCur->data == NULL )
Not sure what is wrong though.
EDIT 2:
I decided i wasn't going to get it working the original way he ask for it before tomorrow morning, so I went a modified version posted here. That one didn't seg fault, but it turns out there was a logic error as well.
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct s
{
int data;
struct s *next;
}node;
void insert_sorted_linked_list(node **head, int val);
void display (node **first);
void freeList(node **first);
int main ()
{
node* first;
int x,y;
first = NULL;
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter number of elements: ");
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(&first,x);
y--;
}
printf ("\nThe sorted list is: ");
display (&first);
freeList(&first);
return 0;
}
void insert_sorted_linked_list(node **head, int val)
{
node* pCur;
node* pNew = (node*) (malloc(sizeof(node)));
pNew->data = val;
pNew->next = NULL;
pCur = (*head);
if( pCur == NULL )
{
(*head) = pNew;
}
else if(pNew->data < pCur->data)
{
pNew->next = pCur;
(*head) = pNew;
}
else
{
while(pCur->next!=NULL && pNew->data > pCur->next->data)
pCur = pCur->next;
pNew->next = pCur->next;
pCur->next = pNew;
}
}
void display (node **first)
{
node *lisprint; /*OR sort *lisprint */
if (*first == NULL)
printf ("\nList is empty");
else
{
lisprint = *first;
while (lisprint != NULL)
{
printf ("-> %d ", lisprint->data);
lisprint = lisprint->next;
}
getch();
}
} /*END OF FUNCTION DISPLAY*/
void freeList(node **first)
{
node *i;
i = *first;
while(i !=NULL)
{
(*first) = (*first)->next;
free(i);
i = *first;
}
}
Thanks!
Please properly format your code! It was a pain in the a** just to see where the error was!
As it is,
/*PROGRAM TO CREATE & THEN DISPLAY THE LINKED LIST IN SORTED FORM*/
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<conio.h>
typedef struct s
{
int data;
struct s *next;
}node;
/* your declaration for typedef was incorrect. We use typedef in C for structures so that we do not have to repeat struct s everytime. Using typedef, we can write node as we do in c++ */
void insert_sorted_linked_list(node **head, int val); /* do not need to return anything, as well as see the parameter. When we want to change a pointer, we pass the address to the pointer, as it results in passing by value */
void display (node **first); /* same here and below */
void freeList(node **first); /* if you don't do this, memory leak!!! */
int main ()
{
node* first; /*OR sort *first,*list,*pass */
int temp,x,y;
first = NULL; /*OR sort *create() */
printf ("\n\nCreating a Linked List\n");
printf ("\nEnter number of elements: "); /* specify what you want the user to enter */
scanf ("%d", &x);
y=x;
while(y>0)
{
scanf ("%d", &x);
insert_sorted_linked_list(&first,x); /*CALLING CREATE FUNCTION, notice the &first*/
y--;
}
printf ("\nThe list after creation is: ");
display (&first);
printf ("\nThe sorted list is: ");
display (&first);
freeList(&first);
return 0;
} /*END OF MAIN*/
void insert_sorted_linked_list(node **head, int val)
{
node* pCur;
node* pNew = (node*) (malloc(sizeof(node)));
pNew->data = val;
pNew->next = NULL;
pCur = (*head);
if( pCur == NULL )
{
(*head) = pNew;
}
else if (pNew->data < pCur->data)
{
pNew->next = pCur ;
(*head) = pNew;
}
}
/*DISPLAY FUNCTION*/
void display (node **first)
{
node *save; /*OR sort *save */
if (*first == NULL)
printf ("\nList is empty");
else
{
save = *first;
while (save != NULL)
{
printf ("-> %d ", save->data);
save = save->next;
}
getch();
}
} /*END OF FUNCTION DISPLAY*/
void freeList(node **first)
{
node *i;
i = *first;
while(i !=NULL)
{
(*first) = (*first)->next;
free(i);
i = *first;
}
}