how to add a newly created node to linklist? - c

here is my code, i can only add the node to the head of the linklist, but how to append to the tail to the linklist? thanks
struct recordNode {
char name[256];
char event[128]; /
float time;
struct recordNode* next;
};
struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;
struct recordNode* createRecord(char* name, char* event, float time) {
temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;
/* link up */
if (aRecordPointer == NULL) {
aRecordPointer = temp;
temp->next = NULL;
} else {
temp->next = aRecordPointer;
aRecordPointer = temp;
}
return aRecordPointer;
}
int main() {
struct recordNode* record = createRecord("1abc", "abc", 12.25);
record = createRecord("2abc", "abc", 25.98);
record = createRecord("3abc", "abc", 52.60);
}
/* now result:
3abc abc 12.25
2abc abc 25.98
1abc abc 52.60
needed result:
1abc abc 52.6
2abc abc 25.98
3abc abc 12.25
*/

Assuming that aRecordPointer is your pointer to the head (first) element of list, you need to iterate the list from head to tail (last).
struct recordNode* createRecord(char* name, char* event, float time){
temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;
temp->next = NULL;
if (aRecordPointer == NULL) {
aRecordPointer = temp;
}
else {
struct recordNode* pLast = aRecordPointer;
/* find the last element */
while(pLast->next != NULL) {
pLast = pLast->next;
}
/* get linked */
pLast->next = temp;
}
return aRecordPointer;
}

Assuming that aRecordPointer is a pointer to the last Node, modify your code as below:
struct recordNode* createRecord(char* name, char* event, float time)
{
temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;
//I have added this line as well.
temp->next = NULL;
/* link up */
if (aRecordPointer == NULL)
{
aRecordPointer = temp;
}
else
{
aRecordPointer->next = temp;
aRecordPointer = temp;
}
return aRecordPointer;
}
Also note that you should always have a pointer to Head (First Node) in order to traverse the linked list later.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void Traverse();
struct recordNode {
char name[256];
char event[128];
float time;
struct recordNode* next;
};
struct recordNode* temp;
struct recordNode* aRecordPointer = NULL;
struct recordNode* createRecord(char* name, char* event, float time) {
struct recordNode * ToTraverseTheLinkedList;
temp = (struct recordNode*)malloc(sizeof(struct recordNode));
strcpy(temp->name, name);
strcpy(temp->event, event);
temp->time = time;
temp->next = NULL;
/* link up */
if (aRecordPointer == NULL) {
aRecordPointer = temp;
//temp->next = NULL;
}
else
{
ToTraverseTheLinkedList = aRecordPointer;
while(ToTraverseTheLinkedList->next != NULL)
{
ToTraverseTheLinkedList = ToTraverseTheLinkedList ->next;
}
ToTraverseTheLinkedList->next = temp;
}
return aRecordPointer;
}
int main() {
createRecord("1abc", "abc", 12.25);
//Traverse();
createRecord("2abc", "abc", 25.98);
createRecord("3abc", "abc", 52.60);
Traverse();
}
void Traverse()
{
struct recordNode * temp;
temp = aRecordPointer;
while(temp != NULL)
{
printf("%s\n",temp->name);
printf("%s\n",temp->event);
printf("%f\n",temp->time);
temp = temp->next;
}
}

Related

Double linked List functions - Driver program failure

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node_t{
int value;
struct node_t *prev;
struct node_t *next;
} Node;
typedef struct LinkedList{
Node *head;
Node *tail;
} LinkedList;
void clearing_space_for_LinkedList(LinkedList *ll){
ll->head = NULL;
ll->tail = NULL;
}
int empty_check(LinkedList *ll){
if(ll->head == NULL){
return 1;
}
else{
return 0;
}
}
void add_element_at_the_beginning(LinkedList *ll, int new_value){
Node *temporary = calloc(1,sizeof(Node));
temporary->value = new_value;
if (empty_check(ll)){
temporary->next = NULL;
temporary->prev = NULL;
ll->head = temporary;
ll->tail = temporary;
}
else{
temporary->next = ll->head;
temporary->prev = NULL;
ll->head->prev = temporary;
ll->head = temporary;
}
}
void add_element_at_the_end(LinkedList *ll, int new_value){
Node *temporary = calloc(1,sizeof(Node));
temporary->value = new_value;
if (empty_check(ll)){
temporary->next = NULL;
temporary->prev = NULL;
ll->head = temporary;
ll->tail = temporary;
}
else{
temporary->next = NULL;
temporary->prev = ll->tail;
ll->tail->next = temporary;
ll->tail = temporary;
}
}
int eliminate_the_first_element(LinkedList *ll){
Node *temporary = ll->head;
ll->head = ll->head->next;
ll->head->prev = NULL;
int result = temporary->value;
free(temporary);
return result;
}
int eliminate_the_last_element(LinkedList *ll){
Node *temporary = ll->tail;
ll->tail = ll->tail->prev;
ll->tail->next = NULL;
free(temporary);
return temporary->value;
}
void eliminate_the_single_element(LinkedList *ll){
Node *temporary = ll->head;
ll->head = NULL;
ll->tail = NULL;
free(temporary);
}
int add_element_on_another_spot(LinkedList *ll, int new_val){
int position = 0;
scanf("%d", &position);
Node *new_node = calloc(1,sizeof(Node));
new_node->value = new_val;
Node *iterator = ll->head;
for(int i = 0; i < position; ++i){
iterator = iterator->prev;
}
new_node->next = iterator;
new_node->prev = iterator->prev;
iterator->prev->next = new_node;
iterator->prev = new_node;
}
void print_the_linked_list(LinkedList *ll){
Node *curr = ll->head;
while (curr){
printf("%d, ", curr->value);
curr = curr->next;
}
printf("\n");
}
LinkedList * ll;
int main(){
clearing_space_for_LinkedList(ll);
add_element_at_the_beginning(ll, 10);
print_the_linked_list(ll);
}
When i try to run it i get Segmentation fault (core dumped)
Can someone explain why am i getting this message ?
And is my algorithm of creating and using double linked list rightly done ?
Also i am having hard time realizing really how to remove element?
Is the used function above correct for creating space for the list or this:
void clearing_space_for_LinkedList(LinkedList *linkedList) {
linkedList = (LinkedList*)calloc(1, sizeof(LinkedList));
linkedList->head = (Node*)calloc(1, sizeof(Node));
linkedList->tail = (Node*)calloc(1, sizeof(Node));
linkedList->head = NULL;
linkedList->tail = NULL;
}
Is it possible to create double linked list with arrays and if yes, how ?
Will just creating array for value in the typdef structure will work ?
Code has at least these problems:
No NULL check
clearing_space_for_LinkedList(LinkedList *ll) attempts ll->head even when ll == NULL which happens on OP's first call.
Code fails on last node elimination
eliminate_the_first_element() makes no provision for setting ll->tail to NULL should the last node get eliminated.
Similar problem with eliminate_the_last_element().

Adding a linked list to another linked list in C programming

I am abeginner trying to add a linked list to another linked list using c. the problem is that the program is entering an infinite loop and i don't know why.
And here's the following c code
typedef struct bookInfo
{
int code;
struct bookInfo *next;
} bookInfo;
typedef struct subscriber
{
int code;
struct bookInfo *books;
struct subscriber *next;
struct subscriber *prec;
} subscriber;
typedef bookInfo *Book;
typedef subscriber *Subscriber;
typedef Subscriber *SubscriberList;
void newBook(Book *bk, int val)
{
bookInfo *new_node = malloc(sizeof(bookInfo));
bookInfo *last = *bk;
new_node->code = val;
new_node->next = NULL;
if (*bk == NULL)
{
*bk = new_node;
}
else
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
}
Subscriber Add_book(Subscriber S, Book Bk)
{
bookInfo *newNode = malloc(sizeof(bookInfo));
bookInfo *tmp;
newNode->next = NULL;
newNode->code = Bk->code;
if (S == NULL)
printf("\nl'abonnee est nulle");
else
{
if (S->books == NULL)
S->books = newNode;
else
{
tmp = S->books;
while (tmp != NULL)
tmp = tmp->next;
tmp->next = newNode;
printf("\nl'ajout du livre a ete effectue");
};
}
return S;
};
Hope you guys can help me and thank you. I don't know if the problem in the function newBook or what and here it's my main function
int main()
{
book_ref, sub_ref = NULL;
newSubscriber(&sub_ref);
bookInfo b1 = {20,NULL};
Add_book(sub_ref, &b1);
printf("\n%d : %d", sub_ref->code, sub_ref->books->code);
}
In your code,
while (tmp != NULL) tmp = tmp->next;
When this loop ends, tmp is NULL, so the next line will try accessing null pointer.
You should correct it as, while(tmp->next != NULL)
In order to remove the infinite loop, All i had to do was to define the pointer of books in the subscriber struct to NULL
void newBook(Book *bk, int val)
{
bookInfo *new_node = malloc(sizeof(bookInfo));
bookInfo *last = *bk;
new_node->code = val;
new_node->next = NULL;
new_node->books = NULL;
if (*bk == NULL)
{
*bk = new_node;
}
else
{
while (last->next != NULL)
last = last->next;
last->next = new_node;
}
}
Subscriber Add_book(Subscriber S, Book Bk)
{
bookInfo *newNode = malloc(sizeof(bookInfo));
bookInfo *tmp;
newNode->next = NULL;
newNode->code = Bk->code;
newNode->books = NULL;
if (S == NULL)
printf("\nl'abonnee est nulle");
else
{
if (S->books == NULL)
S->books = newNode;
else
{
tmp = S->books;
while (tmp != NULL)
tmp = tmp->next;
tmp->next = newNode;
printf("\nl'ajout du livre a ete effectue");
};
}
return S;
};
and everything worked.

I get an error when I initialize a string in a structure

I want to initialize a string with every char of it '\0'.(Because I will use gets() later, the first char being not '\0' is OK.)
So I use assign the string with "a".
Here is my code:
typedef struct node
{
char name[12] = "a";
struct node* next;
struct node* prev;
struct node* lead;
} node;
However,
if I change char name[12] = "a"; tochar name[12]; , it will be OK,
if I don't change, it will give an error message:
C:\UsersDesktop\exp1-2\main.c|7|error: expected ':', ',', ';', '}' or '__attribute__' before '=' token| and C:\Users\Desktop\exp1-2\main.c|25|error: 'node' {aka 'struct node'} has no member named 'name'|
Thank you in advance!
Above shows my part of code, if you wanna see a complete one, HRER are my complete code:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef struct node
{
char name[12] = "a";
struct node* next;
struct node* prev;
struct node* lead;
} node;
node* init()
{
node* huzong = (node*)malloc(sizeof(node));
node* wangzong = (node*)malloc(sizeof(node));
node* zhangzong = (node*)malloc(sizeof(node));
node* lizong = (node*)malloc(sizeof(node));
node* zhangsan = (node*)malloc(sizeof(node));
node* lisi = (node*)malloc(sizeof(node));
node* laoliu = (node*)malloc(sizeof(node));
node* xiaopeng = (node*)malloc(sizeof(node));
node* xiaochen = (node*)malloc(sizeof(node));
strcpy(huzong->name, "胡总");
huzong->lead = NULL;
huzong->prev = NULL;
huzong->next = wangzong;
strcpy(huzong->name, "王总");
wangzong->lead = zhangsan;
wangzong->prev = huzong;
wangzong->next = zhangzong;
strcpy(huzong->name, "张总");
zhangzong->lead = NULL;
zhangzong->prev = wangzong;
zhangzong->next = lizong;
strcpy(huzong->name, "黎总");
lizong->lead = NULL;
lizong->prev = zhangzong;
lizong->next = NULL;
strcpy(huzong->name, "张三");
zhangsan->lead = NULL;
zhangsan->prev = NULL;
zhangsan->next = lisi;
strcpy(huzong->name, "李四");
lisi->lead = xiaopeng;
lisi->prev = zhangsan;
lisi->next = laoliu;
strcpy(huzong->name, "老刘");
laoliu->lead = NULL;
laoliu->prev = lisi;
laoliu->next = NULL;
strcpy(huzong->name, "小彭");
xiaopeng->lead = NULL;
xiaopeng->prev = NULL;
xiaopeng->next = xiaochen;
strcpy(huzong->name, "小陈");
xiaochen->lead = NULL;
xiaochen->prev = xiaopeng;
xiaochen->next = NULL;
return huzong;
}
void list(node* head)
{
printf("%s", head->name);
list(head->lead);
list(head->next);
}
node* find(node* head, char* ex_name)
{
int i = 1;
i = strcmp((head->name), *ex_name);
if(i==0)
{
return head;
}
find(head->lead, ex_name);
find(head->next, ex_name);
return NULL;
}
void lead(node* new_node, node* existing)
{
existing->lead = new_node;
new_node->lead = NULL;
new_node->next = NULL;
new_node->prev = NULL;
}
void follow(node* new_node, node* existing)
{
existing->next = new_node;
new_node->prev = NULL;
new_node->lead = NULL;
new_node->next = NULL;
}
int main()
{
char input[60]="a";
char new_name[12]="a";
char ex_name[12]="a";
while(1)
{
node* head;
node* temp = NULL;
head = init();
gets(input);
for(int i = 0; i < 50; i++)
{
//init初始化实现
if(input[i]=='i'&&input[i+1]=='n'&&input[i+2]=='i'
&&input[i+3]=='t')
{
init();
printf("链表构造完成,现有9名员工");
}
//list遍历功能实现
if(input[i]=='l'&&input[i+1]=='i'&&input[i+2]=='s'
&&input[i+3]=='t')
{
list(head);
}
//lead功能实现
if(input[i]=='l'&&input[i+1]=='e'&&input[i+2]=='a'
&&input[i+3]=='d')
{
for(int j=0; j<=i-2; j++)
{
new_name[j] = input[j];
}
printf("%s", new_name);
for(int k=i+8; k<=i+20; k++)
{
ex_name[k-i-8] = input[k];
}
printf("%s", ex_name);
node* new_node = (node*)malloc(sizeof(node));
strcpy(new_node->name, new_name);
printf("strcpy完成");
temp = find(head, ex_name); //问题在此
printf("find完成");
temp->lead = new_node;
}
}
}
}
Your code is not valid C, as you cannot initialize struct fields in this manner.
char name[12] = "a";
Were you allocating the memory for name dynamically, I'd suggest using calloc which sets all bytes to zero.
For instance:
typedef struct node {
char *name;
...
} node;
node *new_node(char *name) {
node *n = malloc(sizeof(node));
n->name = calloc(12);
strncpy(n->name, name, 11);
return n;
}

Linked list reverse function leads to infinite printing loop

I was writing a C code to reverse a link list. I got into one problem.
If I do not make my next pointer NULL my reverse function works fine, but if I make it null the linked list always keeps printing in the while loop.
Below is the correct program, which works fine.
But if I make *next = NULL, the display function will keep printing in the while loop.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
} *head;
/*************************************************************/
/* */
/* create - Function to create Nodes and add them at last */
/* */
/*************************************************************/
int create(int data)
{
struct node *temp,*ptr = NULL;
//int data = 0;
ptr = head;
//Printf(" Enter the Data for Node : ");
//scanf(" %d ", data);
temp = (struct node *)malloc(sizeof(struct node));
if (ptr == NULL) {
// this is the first node
temp->next = NULL;
temp->data = data;
head = temp;
} else {
// this is not the first node
while (ptr != NULL) {
if (ptr->next == NULL) {
temp->next = NULL;
temp->data = data;
ptr->next = temp;
break;
}
ptr = ptr->next;
}
}
return 0;
}
/*************************************************************/
/* */
/* create_in_front - Function to add Node in Front */
/* */
/*************************************************************/
int create_in_front(int data)
{
struct node *temp,*ptr = NULL;
ptr = head;
temp = (struct node *)malloc(sizeof(struct node));
if (ptr == NULL) {
// this is the first node
temp->next = NULL;
temp->data = data;
head = temp;
} else {
// this is not the first node
temp->next = ptr->next;
temp->data = data;
head = temp;
}
return 0;
}
/*************************************************************/
/* */
/* create_in_between - Function to add Node in between nodes*/
/* */
/*************************************************************/
int create_in_between(int data,int pos)
{
struct node *temp, *ptr = NULL;
int i = 0;
ptr = head;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
for (i = 0; i < pos; i++) {
if (i == pos-1) {
temp->next = ptr->next;
ptr->next = temp;
}
ptr = ptr->next;
}
return 0;
}
/*************************************************************/
/* */
/* delete_in_between - Function to add Node in between nodes*/
/* */
/*************************************************************/
delete_in_between(int pos)
{
struct node *ptr, *prev = NULL;
ptr = head;
int i = 0;
for (i = 0; i < pos; i++) {
if (i == pos-1) {
prev = ptr->next;
free(ptr);
break;
}
prev = ptr;
ptr = ptr->next;
}
return 0;
}
/*************************************************************/
/* */
/* reverse - Function to reverse link list */
/* */
/*************************************************************/
int reverse()
{
struct node *prev = NULL;
struct node *curr = head;
struct node *next = NULL;
curr = head;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
return 0;
}
/*************************************************************/
/* */
/* display - Function to diplay link list */
/* */
/*************************************************************/
// Function to display Link List
int display()
{
struct node *temp = head;
while (temp != NULL) {
printf("%d->",temp->data);
temp = temp->next;
}
return 0;
}
int main()
{
create(10);
create(20);
create(30);
create(40);
create(50);
create_in_front(34);
create_in_between(55,2);
//delete_in_between(4);
reverse();
display();
return 0;
}
Let me know the logic behind this.
Function create_in_front() is bogus: temp->next = ptr->next; should be changed to temp->next = ptr;
create_in_between() does not handle the case of pos==0.
delete_in_between() is completely dysfunctional: the node is frees but its predecessor still points to it.
reverse() seems correct to me, it could be simplified this way:
int reverse() {
struct node *prev = NULL;
struct node *curr = head;
while (curr != NULL) {
struct node *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
return 0;
}
The problem seems unrelated to your modifying the reverse() function, maybe a side effect of bugs in the other functions.
Your reverse() function seems correct, but the rest of the code is somewhat overcomplicated. Try something like this:
void create(int data) {
struct node *temp = malloc(sizeof(struct node));
if (temp != NULL) {
temp->next = NULL;
temp->data = data;
if (head == NULL) { // this is the first node
head = temp;
} else {
// this is not the first node
struct node *last = head;
while (last->next)
last = last->next;
last->next = temp;
}
}
}
void create_in_front(int data) {
struct node *temp = malloc(sizeof(struct node));
if (temp != NULL) {
temp->next = head;
temp->data = data;
head = temp;
}
}

Linked list add() method in C

Where is error the following code?
addNode() function is not run, neither is the traverse() function.
Last data is not shown.
#include <stdio.h>
#include <stdlib.h>
struct isimler{
char isim[10];
struct isimler *next;
};
typedef struct isimler node;
node *head;
void createList(){
int k, n;
node *po;
printf("Eleman Sayisi: "); scanf("%d", &n);
for(k = 0; k<n; k++){
if(k == 0){
head = (node *) malloc(sizeof(node));
po = head;
}else{
po->next = (node *) malloc(sizeof(node));
po = po->next;
}
printf("Isim Girin: "); scanf("%s",po->isim);
}
po->next = NULL;
}
void addNode(){
node *po, *newNode;
po = head;
while(po != NULL){
po = po->next;
}
po = (node *) malloc(sizeof(node));
printf("Isim Girin: "); scanf("%s", po->isim);
po->next = NULL;
}
void traverseList(){
node *po;
int i=0;
po = head;
while(po != NULL){
printf("%d.\t%s\n",i,po->isim);
po = po->next;
i++;
}
}
int main(){
createList();
traverseList();
addNode();
traverseList();
return 1903;
}
Your current addNode() method creates a new node but it doesn't add it to your linked list.
You need to modify your addNode() method like so:
void addNode(){
node *po, *newNode;
po = head;
while(po->next != NULL) { // change this so you don't lose the end of the list
po = po->next; // po is now pointing to the last node in the list
}
newNode = (node *) malloc(sizeof(node)); // change this to newNode
printf("Isim Girin: "); scanf("%s", newNode->isim);
po->next = newNode; // add the new node here, don't set it to NULL
newNode->next = NULL;
}
You can have look this code and get to know where exactly you are having problem
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n");
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true);
print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}

Resources