I think I got it wrong in newList. Typedef struct implementations must not be change. This is a lab assignment in my school.. Thanks in advance :)
#include<stdio.h>
typedef struct node *nodeptr;
struct node {
int item;
nodeptr next;
};
typedef nodeptr List;
List newList();
newList creates a header and returns a pointer to the header node
void display(List list);
void addFront(List list, int item);
List newList(){
List list;
list=(nodeptr)malloc(sizeof(List));
list->next=NULL;
return list;
} //I think my new list is incorrect..
void display(List list){
nodeptr ptr=list;
while(ptr!=NULL){
printf("%d",ptr->item);
ptr=ptr->next;
}
printf("\n");
}
void addEnd(List list, int item){
nodeptr temp, ptr;
temp=(List)malloc(sizeof(nodeptr));
temp->item=item;
temp->next=NULL;
if(list->next==NULL)
list=temp;
else{
ptr=list;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=temp;
}
}
I can't seem to add 10 from the list..
int main(void){
List list=newList();
addEnd(list,10);
display(list);
}
There are many ways you can go about this depending on what you actually want (because just creating a node doesn't make a lot of sense by itself). But generally you have three common options — create it on the stack, create that node in the global memory, or allocate it dynamically. Below are some examples.
On stack
#include <stdlib.h>
struct node {
int item;
struct node *next;
};
int main()
{
struct node head;
head.item = 0;
head.next = NULL;
/* Do something with the list now. */
return EXIT_SUCCESS;
}
In Global Memory
#include <stdlib.h>
struct node {
int item;
struct node *next;
};
static struct node head;
int main()
{
/* Do something with the list now. */
return EXIT_SUCCESS;
}
Dynamic Allocation
#include <stdlib.h>
#include <stdio.h>
struct node {
int item;
struct node *next;
};
int main()
{
struct node *head;
head = calloc(1, sizeof(struct node));
if (head == NULL) {
perror("calloc");
return EXIT_FAILURE;
}
/* Do something with the list now. */
return EXIT_SUCCESS;
}
You can read up on any of the above example in any introductory C book.
Hope it helps. Good Luck!
Related
I want to createe a list of nodes that links to each other, I use head to remember the address of the first node, prev to link, and newdata to get the input, but it turns out that my head prev and newdata are all in the same address, can someone help me with this plz
typedef struct node
{
void* stdPtr;
struct node* link;
}NODE;
NODE* createNode(void* std)
{
NODE* nodePtr;
nodePtr=(NODE*)malloc(sizeof(NODE));
nodePtr->stdPtr=std;
nodePtr->link=NULL;
return nodePtr;
}
typedef NODE* nodePtr;
int main(void)
{
FILE* fin;
fin=fopen("input.txt","r");
//define
int i=0;
intPtr ID,grade;
STD* stdinfo;
nodePtr head=NULL;
nodePtr prev=(nodePtr)malloc(sizeof(NODE));
//nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
prev=head;
//malloc space to ptr
ID=(intPtr)malloc(sizeof(int));
grade=(intPtr)malloc(sizeof(int));
stdinfo=(STD*)malloc(sizeof(STD));
//read student data and compare
while(fscanf(fin,"%d%d",&(stdinfo->ID),&(stdinfo->grade))!=EOF)
{
nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
newdata=createNode(stdinfo);
if (prev==NULL)
{
prev=newdata;
head=prev;//為什麼只有在這裡=prev後面會跑掉?
}
printf("%d %d\n",*(int*)head,*(int*)prev);
if(prev->link!=NULL)
{
prev=prev->link;
}
prev->link=newdata;
}
fclose(fin);
return 0;
}
Important parts are missing (types, input.txt) to run your program which makes it harder to help you.
You create an instance of STD prior to the loop, then overwrite whatever data you store in it on each iteration and store the address of that one instance in each node. You need to create an instance of both NODE and STD per loop iteration (or change the definition of NODE so it can hold the STD data instead of a pointer to STD).
You use this pattern a couple of times which allocate data, then immediately leak the data by overwriting the pointer:
nodePtr prev=(nodePtr)malloc(sizeof(NODE));
prev=head;
...
nodePtr newdata=(nodePtr)malloc(sizeof(NODE));
newdata=createNode(stdinfo);
Here is more straight forward version to get you going:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
void *stdPtr;
struct node* link;
} NODE;
NODE* createNode(void *std, NODE *prev) {
NODE *nodePtr = malloc(sizeof(NODE));
nodePtr->stdPtr=std;
nodePtr->link=prev;
return nodePtr;
}
void printNodes(NODE *tail) {
for(; tail; tail = tail->link) {
printf("%s\n", (const char *) tail->stdPtr);
}
}
int main(void) {
NODE *tail = NULL;
tail = createNode("hello", tail);
tail = createNode("world", tail);
printNodes(tail);
}
I want to create a function that search for a certain value in a linked list and then put the node containing it and the node before the one containing it in two separate nodes.
This is my code and I can't figure out why it does not work:
#include <stdio.h>
#include <stdlib.h>
struct node{
int val;
struct node* next;
};
typedef struct node node_t;
void printlist(node_t *head){
node_t *temp=head;
while (temp!=NULL){
printf("%d -",temp->val);
temp=temp->next;
}
printf("\n");
}
node_t *create_new_node(int value){
node_t *result=malloc(sizeof(node_t));
result->val=value;
result->next=NULL;
return result;
}
void *insert_after_node(node_t *node_to_insert,node_t *newnode){
newnode->next=node_to_insert->next;
node_to_insert->next=newnode;
}
void *find_node(node_t *head,int value,node_t *R,node_t *RA){
node_t *tmp=head;
while (R!=NULL && tmp!=NULL){
if (tmp->val==value)
R=tmp;
else{
RA=tmp;
tmp=tmp->next;
}
}
}
int main(){
node_t *head=NULL;
node_t *tmp;
node_t *R=NULL;
node_t *RA=NULL;
for (int i=0;i<25;i++){
tmp=create_new_node(i);
insert_at_head(&head,tmp);
}
find_node(head,13,R,RA);
printlist(head);
printlist(RA);
printlist(R);
}
Thank you !
You want to pass in the addresses of R and RA to find_node. And declare the params as **
void *find_node(node_t *head,int value,node_t **R,node_t **RA){
and then use (*R/ *RA) in the function
Call with
find_node(head,13,&R,&RA);
In your version, find_node cannot reassign the pointers passed in.
I created the following library to insert,delete,search and print nodes in a binary tree.
#include <stdlib.h>
struct NODE
{
int code;
char subject[20];
struct NODE *left;
struct NODE *right;
};
void InOrder(struct NODE *R)
{
if (R==NULL)
return;
InOrder(R->left);
printf("%d %s\n",R->code,R->subject);
InOrder(R->right);
}
void PreOrder(struct NODE *R)
{
if (R==NULL)
return;
printf("%d %s\n",R->code,R->subject);
InOrder(R->left);
InOrder(R->right);
}
void PostOrder(struct NODE *R)
{
if (R==NULL)
return;
InOrder(R->left);
InOrder(R->right);
printf("%d %s\n",R->code,R->subject);
}
struct NODE *Search(struct NODE *R,int CODE,struct NODE **father)
{
if(R==NULL)
return NULL;
if(R->code==CODE)
{
*father=R;
return R;
}
if (CODE<R->code)
return Search(R->left,CODE,father);
else
return Search(R->right,CODE,father);
}
struct NODE * CreateNode(struct NODE T)
{
struct NODE *tmp;
tmp=(struct NODE *)malloc(sizeof(T));
*tmp=T;
tmp->left=tmp->right=NULL;
return tmp;
}
int Insert(struct NODE **R,struct NODE ND)
{
struct NODE *cur,*fath=NULL;
cur=Search(*R,ND.code,&fath);
if (cur)
return 0;
cur=CreateNode(ND);
if(fath==NULL)
*R=cur;
else
if(fath->code>ND.code)
fath->left=cur;
else
fath->right=cur;
return 1;
}
struct NODE *MinOfMax (struct NODE *ND)
{
struct NODE *tmp;
if (ND==NULL)
return NULL;
if(ND->right==NULL)
return NULL;
tmp=ND->right;
while(tmp->left!=NULL)
tmp=tmp->left;
return tmp;
}
struct NODE* Delete(struct NODE *R, int code)
{
if (R==NULL)
return R;
if (code<R->code)
R->left=Delete(R->left,code);
else if (code>R->code)
R->right=Delete(R->right,code);
else
{
if (R->left==NULL)
{
struct NODE *temp=R->right;
free(R);
return temp;
}
else if (R->right==NULL)
{
struct NODE *temp=R->left;
free(R);
return temp;
}
struct NODE *temp=MinOfMax(R->right);
R->code=temp->code;
R->right=Delete(R->right,temp->code);
}
return R;
}
When i try to insert a node in the binary tree,the program crashes.Here is my main:
int main(int argc,char* argv[])
{
typedef struct NODE NODE;
NODE *root=NULL;
NODE tmp;
Insert(&root,tmp);
return 0;
}
I tried to assign static values (for example code=100 and subject="Physics") but still the program crashes.Should i malloc something,change anything in my header file or do something entirely different?I'm stuck here for hours without finding any solution.Most insert functions out there assume that i only have one integer as data in the node,but i need to pass the entire node.
Your code basically does nothing. It seems you copy-pasted it from somewhere. I tried to figure it out and here's a code example. Basically you've to initializate a new node in the main when you try to insert it.
Note that's just an example, i didn't a full test.
int main(int argc,char* argv[])
{
typedef struct NODE NODE;
NODE *root=NULL;
NODE *tmp = malloc(sizeof(struct NODE));
tmp->code = 1; /*Just a number*/
strcpy(tmp->subject,"prova"); /*Put something in it*/
Insert(&root,*tmp); /* Try to insert it*/
PreOrder(root); /*Try to see if it has been inserted*/
return 0;
}
Your tmp node, which is going to be the newly inserted node is used uninitialized in your main(). Your compiler could have warned you for this, if you had used -Wall flag.
So let's take a look in your insert function:
int Insert(struct NODE **R, struct NODE ND)
{
struct NODE *cur,*fath=NULL;
cur = Search(*R, ND.code, &fath); // ND.code is junk, since ND is uninitialized
...
return 1;
}
which likely causes the segmentation fault.
root is too, you could initialize it to NULL in main().
Not the cause of your problem, but Do I cast the result of malloc? No.
I have problems with understanding the whole concept of this. The major issue that confuses me is the the pointer inside a struct inside a struct... Basically what I understand is that I am wanting to create a chain of nodes.
When I run this program it crashes after two seconds. I believe there is something wrong with my structure in main.c, because I have created it by myself and as you can see I am really Bambi on thin ice over here...
main.c
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "list.h"
// I guess my struct is not correct
static struct {
LIST node;
int item;
} node;
int main() {
list_create();
list_append(node.node, node.item);
}
list.h
typedef struct node* LIST;
LIST list_create (void);
void list_append (LIST l, int item);
list.c
struct node* list_create() {
struct node* head = (struct node*) malloc(sizeof (struct node));
head->next = NULL;
return head;
}
void list_append(struct node* n, int item)
{
/* Create new node */
struct node* new_node = (struct node*) malloc (sizeof (struct node));
new_node->item = item;
/* Find last link */
while (n->next) {
n = n->next;
}
/* Joint the new node */
new_node->next = NULL;
n->next = new_node;
}
At first, node is use for create a structure with data and in THIS data you have a pointer to another struct.
static struct {
LIST node;
int item;
} node;
Actually your structure is incorrect.
You must create at beginning a structure with your data for example :
static struct node{
int item;
};
then put a pointer to the similar structure but will not have same data =>
static struct node{
struct node *next;
int item;
};
You will can use this pointer to manipulate other & other structure.
I see another problem in your main :
You call the function "list_create()" which return a pointer to structure but you assign nothing.
you must create a pointer to struct then assign it like this :
int main() {
struct node *list;
list = list_create();
}
This code works completely (you can put it all in one C file; annotations in the code):
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
/* I removed the "static", because what we want is a type,
not a global static variable */
/* This "node" is our list-element. It has a pointer to a next element, and
some data, in this case, an int. */
typedef struct node {
struct node *next;
int item;
} node;
/* For convenience, another type, a pointer to a node. */
typedef node *LIST;
/* Creating a list is as simple as creating a node, and make the "next"
pointer NULL, you got this correct. */
struct node* list_create() {
struct node* head = (struct node*) malloc(sizeof (struct node));
head->next = NULL;
return head;
}
/* Nothing wrong in this append code. */
void list_append(struct node* n, int item)
{
/* Create new node */
struct node* new_node = (struct node*) malloc (sizeof (struct node));
new_node->item = item;
/* Find last link */
while (n->next) {
n = n->next;
}
/* Joint the new node */
new_node->next = NULL;
n->next = new_node;
}
/* I added this to make sure it works :) */
void print_list(LIST l) {
LIST tmp = l;
while (tmp) {
printf("%d\n", tmp->item);
tmp = tmp->next;
}
/* Here are some changes. I create a local LIST (which is basically a pointer
to a node, remember?) and use list_create to initialise it. Then, I call
list_append two times to put some extra data into it.
Works perfectly! */
int main() {
LIST myList = list_create();
list_append(myList, 10);
list_append(myList, 13);
print_list(myList);
}
You are calling list_create, but not using its result.
I try to print a linked list but it didn't print all of the member in the list.can you explain what is the issue in my code? is code line (newhead=newhead->next) moves even the rest of the list is on the another function?
#include <stdio.h>
#include <stdlib.h>
struct test_struct{
int data;
struct test_struct *next;
};
struct test_struct* create();
void add_node();
int main()
{
add_node();
return 0;
}
void add_node()
{
struct test_struct* head = create();
struct test_struct* newhead;
newhead = malloc(sizeof(struct test_struct));
newhead->data=2;
newhead->next=head;
head=newhead;
while(newhead->next != NULL)
{
printf("%d\n",newhead->data);
newhead=newhead->next;
}
}
struct test_struct* create()
{
struct test_struct* head=NULL;
struct test_struct* temp = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL==temp)
{
printf("error in memory");
return 0;
}
temp->data=5;
temp->next=head;
head=temp;
return head;
}
Your while loop stops when it is on a node with no next node; it doesn't print the data on that node.
Instead, you want to stop when it is pointing to no node; that is, just after it's "fallen off the end" of your list:
while(newhead != NULL)
{
printf("%d\n",newhead->data);
newhead=newhead->next;
}
Line 26 should be while (newhead != NULL).
If you want to keep growing this, you could also review the purpose of each function, since add_node() and create() are doing almost the same thing, plus add_node() also prints the list, which could be the purpose of a separate function.