doubly linked list problem with removal and push back maybe - c

In the main function, I tried to push front couple numbers and push back couple numbers and then remove pos = 0 and pso = 1. However, in the output, remove at pos = 0 and remove at pos = 1 prints out number 5 and number 7 which are wrong. It should be 4 and 2. I cannot find which part I am wrong. Here is my code:
#ifndef MYDLL_H
#define MYDLL_H
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
struct node *previous;
} node_t;
typedef struct DLL
{
int count;
node_t *head;
node_t *tail;
} dll_t;
dll_t *create_dll()
{
dll_t *myDLL = (dll_t*)malloc(sizeof(dll_t));
if (myDLL == NULL) {
return NULL;
}
myDLL->count = 0;
myDLL->head = NULL;
myDLL->tail = NULL;
return myDLL;
}
int dll_empty(dll_t *l)
{
if (l == NULL) {
return -1;
}
if (l->count == 0 && l->head == NULL) {
return 1;
} else {
return 0;
}
}
int dll_push_front(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->next = l->head;
new->previous = NULL;
if (l->head != NULL) { //set new prev for the previous head before pushing.
l->head->previous = new;
}
l->head = new; // reset the new head for l.
l->count++;
return 1;
}
int dll_push_back(dll_t *l, int item)
{
if (l == NULL) {
return -1;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return -1;
}
new->data = item;
new->previous = l->tail;
new->next = NULL;
if(l->tail != NULL) {
l->tail->next = new;
} else {
l->head = new;
}
l->tail = new;
l->count++;
return 1;
}
int dll_pop_front(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->head;
int pop_item = pop_pointer->data;
t->head = pop_pointer->next; // set new head.
if (t->head != NULL) {
t->head->previous = NULL;
} else { // t->head = NULL cuz only one item and after popping, the t->head is null.
t->tail = NULL; // else if t->head = NULL, then t->tail also should be NULL.
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_pop_back(dll_t *t)
{
if (t == NULL || t->head == NULL) {
return -1;
}
node_t* pop_pointer = t->tail;
int pop_item = pop_pointer->data;
t->tail = pop_pointer->previous;
if (t->tail != NULL) {
t->tail->next = NULL;
} else {
t->head = NULL;
}
if (t->head == NULL) {
t->tail = NULL;
}
t->count--;
free(pop_pointer);
return pop_item;
}
int dll_insert(dll_t *l, int pos, int item)
{
if (l == NULL) {
return -1;
}
if (pos >= l->count || pos < 0) {
return 0;
}
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL) {
return 0;
}
new->data = item;
if(pos == 0) {
return dll_push_front(l, item);
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
//ex: pos = 1, no for loop, pointer still head.
new->previous = pointer;
new->next = pointer->next;
pointer->next->previous = new;
pointer->next = new;
l->count++;
return 1;
}
int dll_get(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
for (int i = 0; i < pos - 1; i++) {
pointer = pointer->next;
}
return pointer->data;
}
int dll_remove(dll_t *l, int pos)
{
if (l == NULL) {
return -1;
}
if (pos < 0 || pos >= l->count) {
return 0;
}
node_t* pointer = l->head;
node_t* prev = NULL; // first node prev is null.
for (int i = 0; i < pos; i++) {
prev = pointer;
pointer = pointer->next;
}
if (prev == NULL) { // first item.
l->head = pointer->next;
} else {
prev->next = pointer->next;
}
if (pointer->next != NULL) {
pointer->next->previous = prev;
}
// if we are removing the tail node
if (pointer == l->tail) {
l->tail = prev;
}
int removed_value = pointer->data;
free(pointer);
l->count--;
return removed_value;
}
int dll_size(dll_t *t) {
if (t == NULL) {
return -1;
}
return t->count;
}
void free_dll(dll_t *t)
{
if (t == NULL) {
return;
}
if (t == NULL) {
free(t);
return;
}
node_t* pointer = t->head;
while(pointer != NULL) {
node_t* pointer2 = pointer;
pointer = pointer->next;
free(pointer2);
}
free(t);
}
#endif

Related

it is a binary search tree .there is an issue while deleting elements.why?

it is a binary search tree with inorder traversal. there is an issue while printing elements. I can't solve the issue. The deletebst is not working. It still displays same. It could be a semantic error also. Maybe there is issue in inserting. Or some issue in displaying inorderly.
I am using a double pointer in the search function and calling it in delete function.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *llink;
struct node *rlink;
};
typedef struct node bstnode;
bstnode *root = NULL;
void
insert(int ele)
{
bstnode *cur,
*prev,
*temp;
temp = (bstnode *) malloc(sizeof(bstnode));
temp->data = ele;
temp->llink = temp->rlink = NULL;
cur = root;
prev = NULL;
if (root == NULL)
root = temp;
else {
while (cur != NULL) {
prev = cur;
if (ele < cur->data)
cur = cur->llink;
else
cur = cur->rlink;
}
if (ele < prev->data)
prev->llink = temp;
else
prev->rlink = temp;
}
}
void
inorder(bstnode * node)
{
if (node == NULL) {
return;
}
else if (node != NULL) {
inorder(node->llink);
printf("%d\n", node->data);
inorder(node->rlink);
}
}
bstnode *
search(int key, bstnode ** prev)
{
bstnode *cur;
(*prev) = NULL;
cur = root;
while (cur != NULL) {
if (key == cur->data)
return cur;
else {
(*prev) = cur;
if (key < cur->data)
cur = cur->llink;
else {
cur = cur->rlink;
}
}
}
return cur;
}
void
deletebst(int ele)
{
bstnode *cur,
*prev,
*insucc,
*inprev;
cur = search(ele, &prev);
if (cur->llink != NULL && cur->rlink != NULL) {
inprev = cur;
insucc = cur->rlink;
while (insucc->llink != NULL) {
inprev = insucc;
insucc = insucc->llink;
}
cur->data = insucc->data;
if (inprev == cur) {
inprev->rlink = insucc->rlink;
}
else
inprev->llink = insucc->rlink;
free(insucc);
return;
}
if (cur->llink != NULL && cur->rlink != NULL) {
if (cur == root) {
root = cur->rlink;
}
else if (prev->llink == cur)
prev->llink = cur->llink;
else {
prev->rlink = cur->llink;
}
cur = NULL;
free(cur);
return;
}
if (cur->llink == NULL && cur->rlink == NULL) {
if (cur == root)
root = NULL;
else if (prev->llink == cur)
prev->llink = NULL;
else {
prev->rlink = NULL;
}
return;
}
}
int
main()
{
insert(45);
insert(76);
insert(85);
deletebst(76);
inorder(root);
}

delete element from a list

#include <stdio.h>
#include <malloc.h>
struct el {
int info;
struct el* next;
};
struct el* create_el(struct el* Li)
{
int num;
printf("\n\nInsert number:\n\n");
scanf("%d", &num);
Li = (struct el*)malloc(sizeof(struct el));
if (Li != NULL) {
Li->info = num;
Li->next = NULL;
}
return (Li);
}
struct el* push(struct el* L, struct el* e)
{ //inserts the elements from the head of the list
if (L == NULL)
return (e);
else {
e->next = L;
L = e;
return (L);
}
}
void visualize(struct el* primo)
{
printf("\n\nList-->");
while (primo->next != NULL) {
printf("%d", primo->info);
printf("-->");
primo = primo->next;
}
if (primo->next == NULL)
printf("%d-->NULL", primo->info);
}
struct el* cancel(struct el** P, int val)
{ //delete element
struct el* prec = NULL;
struct el* curr = (*P);
if (P == NULL) //case empty list
return NULL;
else if (prec == NULL) {
if (curr->info == val) { //case 2 : if the element is the head
(*P)->next = curr->next;
free(curr);
curr = NULL;
}
}
else {
while ((curr != NULL) && (curr->info != val)) {
prec = curr;
curr = curr->next;
}
if (curr->next == NULL && curr->info == val) { // case 3: the elemnt is the last one
prec->next = NULL;
free(curr);
curr = NULL;
return (prec);
}
else {
if (curr->info == val) { //other cases
prec->next = curr->next;
free(curr);
curr = NULL;
return (prec);
}
}
}
}
int main()
{
struct el* head = NULL;
struct el* element;
struct el* list = NULL;
int i, n;
int elem;
printf("Insert the number of elements for the list:\n\n");
scanf("%d", &n);
for (i = 0; i <= n; i++) {
element = create_el(head);
if (element != NULL) {
list = push(list, element);
}
}
visualize(list);
printf("\n\nInsert the element that you want to cancel:");
elem = scanf("%d", &elem);
cancel(&list, elem);
visualize(list);
}
All I've wanted to do was delete an element from a listr, but after all the procediment the list is printed without any modification.
Can anyone see whats wrong in the function cancel(which is meant to delete an element by including any possible position of it)?
In your function cancel, P is definitely not NULL (assuming OS has assigned it an address initially).
prec is NULL the before execution enters if loop.
So, execution executes the line
if(curr->info==val)
Now, if the value, val, you have provided doesn't match curr->info then execution exits the function without deleting any node.

Generalized Linked List: Adding Child Link whenever an opening bracket occurs

Here is my code for generating a GLL for the string input: a,(b,c),d where (b,c) will be linked as a child at the next link of a.
GLL* generateList(char poly[])
{
GLL* newNode = NULL, *first = NULL, *ptr = NULL;
while (poly[i] != '\0')
{
if (poly[i] == ')')
{
return first;
}
else
{
if (poly[i] != ',')
{
if (poly[i] != '(')
{
newNode = createNode(poly[i], 0);
}
else
{
++i;
newNode = createNode('#', 1);
newNode->dlink = generateList(poly);
}
}
}
if (first != NULL)
{
ptr = first;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newNode;
}
else
{
first = newNode;
}
i++;
}
return first;
}
And here is the structure I used for each node.
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
I am not finding a way to add that child link to the parent link whenever the bracket opens. The programs runs in a loop.
Note: I have declared i=0 as a global variable to hold the position of character.
Edit: Here is the createNode function
GLL* createNode(char value, int flag)
{
GLL* newNode;
newNode = (GLL *) malloc(sizeof(GLL)*1);
newNode->data = value;
newNode->dlink = NULL;
newNode->tag = flag;
newNode->next = NULL;
return newNode;
}
How do I do it then?
You could do something like that:
#include <stdbool.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct gll
{
int tag;
struct gll* next;
char data;
struct gll* dlink;
} GLL;
GLL* createNode(char value, int flag)
{
GLL* newNode = calloc(1, sizeof(*newNode));
if (!newNode)
return NULL;
newNode->tag = flag;
newNode->data = value;
return newNode;
}
void freeList(GLL *list)
{
for (GLL *current_node = list, *temp; current_node; current_node = temp) {
temp = current_node->next;
freeList(current_node->dlink);
free(current_node);
}
}
GLL* generateList(char *poly, size_t *pos)
{
size_t const length = strlen(poly);
GLL *head = NULL;
GLL *tail = NULL;
for (; *pos < length; ++*pos) {
if (poly[*pos] == '(') {
++*pos; // don't have the next called generateList() read '(' again
tail->dlink = generateList(poly, pos);
if (!tail->dlink) {
freeList(head);
return NULL;
}
continue;
}
else if (poly[*pos] == ')') {
return head;
}
else if (isalpha((char unsigned)poly[*pos])) {
if (!head) {
head = tail = createNode(poly[*pos], 0);
}
else {
tail->next = createNode(poly[*pos], 0);
tail = tail->next;
}
continue;
}
else if (poly[*pos] == ',')
continue;
fputs("Format error :(\n\n", stderr);
freeList(head);
return NULL;
}
return head;
}
void printList(GLL *list)
{
for (GLL *node = list; node; node = node->next) {
printf("%c ", node->data);
if (node->dlink) {
putchar('(');
printList(node->dlink);
printf("\b) ");
}
}
}
int main(void)
{
size_t pos = 0;
GLL *list = generateList("a,(b,(c,d,e(f)),g,h),i,j,k", &pos);
printList(list);
putchar('\n');
freeList(list);
}
Output
a (b (c d e (f)) g h) i j k
Also, if flag is true then it means that the data is not to be considered but there is a child list to be linked.
Sorry, but I don't get how there could be a child list if there is no data for the node.

circular linked list not working properly in c windows

I tried to implement circular linked list to manage a set of tasks by a server side application. The application is multi-threaded where one thread (updater() ) reads the linked list only for read while another two (push_stream() and delete_stream()) access the linked list to add to and delete from the linked list respectively.
My problem is not all the files to be deleted (after being processed) are deleted.
struct data_stream
{
bool processed;
int count;
char filename[30];
int TYPE_GRP;
int task_type;
struct data_stream *next;
};
struct data_stream *stream_head=NULL; //global variable
main(partial code)
main()
{
_beginthread(updater, 0, NULL);
while ((new_socket = accept(srv_sock, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
_beginthreadex(0, 0, handle_client, &new_socket, 0, 0);
}
}
handle_client function (partial code)
handle_client()
{
//some where in handle_client
EnterCriticalSection(&stream_lock);
stream_head = push_stream(&stream_head, TYPE_GRP, task_type);
LeaveCriticalSection(&stream_lock);
}
updater function (full source code)
void updater(void *data)
{
while (1)
{
struct data_stream*temp = stream_head;
struct data_stream*first = stream_head;
struct data_stream*prev = NULL;
if (stream_head != NULL)
{
struct data_stream*next = NULL;
do
{
next = temp->next;
if (temp->processed == false&&temp->task_type == 2)
{
process_files(temp);
}
else if (temp->processed == false&&temp->task_type == 3)
{
process_others();
}
EnterCriticalSection(&stream_lock);
temp->processed = true;
LeaveCriticalSection(&stream_lock);
temp = next;
} while (temp != first);
}
if (stream_head != NULL)
{
EnterCriticalSection(&stream_lock);
stream_head=delete_stream(&stream_head);
LeaveCriticalSection(&stream_lock);
}
Sleep(6000);
}
}
process_files
void process_files(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
printf("\nerror opening file\n");
}
process_others()
void process_others(struct data_stream*temp)
{
int count = 0;
char file_to_update[50] = { NULL };
size_t name_len = strlen(temp->filename);
memcpy_s(file_to_update, name_len, temp->filename, name_len);
file_to_update[name_len] = '\0';
temp->count = 0;
FILE *list_to_update ;
fopen_s(&list_to_update , file_to_update, "r+b");
if (list_to_update != NULL)
{
char readline[100] = { '\0' };
while (fgets(readline, sizeof(readline), list_to_update ) != NULL)
{
//read a line at a time and process the list
count++;
}
temp->count = count;
fclose(list_to_update );
}
else
{
printf("\nerror opening file\n");
}
}
}
push_stream (full source code)
struct data_stream* push_stream(struct data_data_stream**head_ref, int typ_grp, int task_type)
{
struct data_stream*new_data_stream=
(struct data_data_stream*)malloc(sizeof(struct data_stream));
new_stream->processed = false;
new_stream->task_type = task_type;
new_stream->TYPE_GRP = typ_grp;
new_stream->filename[0] = NULL;
new_stream->count = 0;
new_stream->next = NULL;
if (task_type == 2)
sprintf_s(new_stream->filename, "%s%03d.txt", "file_md5_list_", stream_count);
else
sprintf_s(new_stream->filename, "%s%03d.txt", "other_list_", stream_count);
if (*head_ref == NULL)
{
*head_ref = new_stream;
new_stream->next = new_stream;
}
else
{
struct data_stream* last = (*head_ref)->next;
struct data_stream* prev = (*head_ref)->next;
while (last != *head_ref)
{
prev = last;
last = last->next;
}
new_stream->next = *head_ref;
last->next = new_stream;
}
if (stream_count > 998)
stream_count = 1;
else
stream_count++;
return new_stream;
}
delete_stream function (full source code)
struct data_stream* delete_stream(struct data_data_stream**head)
{
if (head == NULL)
return NULL;
struct data_stream*prev = NULL;
struct data_stream*temp = *head;
struct data_stream*first = *head;
do
{
struct data_stream*next = temp->next;
if (temp->processed)
{
if (prev == NULL)
*head = temp->next;
else
prev->next = temp->next;
char file_to_delete[50] = { NULL };
memcpy_s(file_to_delete, strlen(temp->filename), temp->filename, strlen(temp->filename));
DeleteFileA(file_to_delete);
free(temp);
}
else
{
prev = temp;
}
temp = next;
} while (temp != first);
if (prev == NULL)
{
return NULL;
}
return *head;
}

C two-way list deleting items

I have a problem. The code below creates a two-way looped list. When I want to delete an item of specyfic key value, everything goes right. The problem comes when I want to add an item after deleting another one. It just doesn't appear when I display the list. Do you have any ideas why?
#include <iostream>
#include <time.h>
#include <vector>
#include <stdlib.h>
struct List
{
int key;
double val1, val2, val3;
struct List *next, *prev;
}*element, *temp, *head;
bool ifrepeat = false,ifdelete;
void AddOne(struct List *&head1, int x)
{
List *tmp = head1;
if (head1 != NULL)
{
do
{
if (head1->key == x)
{
ifrepeat = true;
}
head1 = head1->next;
} while (head1 != tmp);
}
if (ifrepeat)
{
printf("Podana wartosc klucza juz istnieje!\n");
ifrepeat = false;
}
else
{
head1 = tmp;
if (head1 == NULL)
{
head1 = (struct List*)malloc(sizeof(struct List));
head1->key = x;
head1->val1 = 1 + (rand() % 1000);
head1->val2 = 1 + rand() % 1000;
head1->val3 = 1 + rand() % 1000;
head1->next = head1;
head1->prev = head1;
}
else
{
if (element == NULL)
{
element = (struct List*)malloc(sizeof(struct List));
element->key = x;
head->next = element;
element->prev = head1;
element->next = head1;
head1->prev = element;
temp = element;
}
else
{
element = (struct List*)malloc(sizeof(struct List));
element->key = x;
temp->next = element;
element->prev = temp;
element->next = head1;
head1->prev = element;
temp = element;
}
}
}
}
void ShowBegin(struct List *head)
{
if (head == NULL)
printf("Lista jest pusta!");
else
{
struct List *temphead;
temphead = head;
printf("%d ", head->key);
head = head->next;
while (head != temphead)
{
printf("%d ", head->key);
head = head->next;
}
printf("\n");
}
}
void AddMany(struct List *&head1, int x)
{
AddOne(head, 10+(rand()%1000)*(rand()%1000));
int tmpkey;
List *tmp = head1;
for (int i = 0; i < x; i++)
{
tmpkey = 10 + (rand() % 100)*(rand() % 1000);
while (head1 != tmp)
{
while (head->key == tmpkey)
{
tmpkey = 10 + (rand() % 100)*(rand() % 1000);
head1 = tmp;
}
head1 = head1->next;
}
AddOne(head, tmpkey);
head1 = tmp;
head1 = head1->next;
}
}
void Sort(struct List *&head1)
{
int max;
List *maxPos,*tmp;
maxPos = head1;
max = head1->key;
while (true)
{
head1 = head1->next;
if (head1->key > max)
{
tmp = head1;
head1 = maxPos;
maxPos = tmp;
max = maxPos->key;
head1 = head;
}
}
}
void CreateList()
{
head = NULL;
element = NULL;
temp = NULL;
}
void Delete(struct List *&head1, int x)
{
struct List *temphead;
temphead = head1;
if (head == NULL)
{
printf("Lista jest pusta!\n");
return;
}
else
{
head1 = head1->next;
if (head1 == temphead)
{
if (head1->key == x)
{
free(head1);
head1 = NULL;
ifdelete = true;
}
else
ifdelete = false;
}
else
{
while (head1 != temphead)
{
if (head1->key == x)
{
List *temp;
temp = head1;
head1->prev->next = head1->next;
head1->next->prev = head1->prev;
head1 = head1->next;
while (head1 != temphead)
{
}
free(temp);
ifdelete = true;
break;
}
else
ifdelete = false;
head1 = head1->next;
}
}
if (!ifdelete)
{
printf("Element o podanym kluczu nie istnieje!\n");
}
}
}
void ShowEnd(struct List *&head)
{
if (head == NULL)
printf("Lista jest pusta!");
else
{
struct List *temphead;
temphead = head;
head = head->prev;
while (head != temphead)
{
printf("%d ", head->key);
head = head->prev;
}
printf("%d", temphead->key);
printf("\n");
}
}
void DeleteAll(struct List *&head)
{
free(head);
head = NULL;
}
int main()
{
int X=1000, k1=5, k2=2, k3=10, k4=-1;
/*FILE* plik = fopen("inlab02.txt", "r");
if (plik == NULL)
return -257;
fscanf(plik, "%d %d %d %d %d", &X, &k1, &k2, &k3, &k4);
fclose(plik);*/
srand(time(NULL));
clock_t begin, end;
double time_spent;
begin = clock();
CreateList();
Delete(head, k1);
ShowBegin(head);
AddMany(head, 10);
AddOne(head, k2);
Delete(head, k2);
AddOne(head, k4);
//Delete(head, k4);
ShowBegin(head);
//ShowEnd(head);
//DeleteAll(head);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Program wykonal obliczenia w %f", time_spent);
getchar();
return 0;
}

Resources