Deleting elements with largest values from linked list - c

I have a problem with deleting elements with greatest values from doubly linked list. It seems that my program works fine with only one greatest number in the list. However, if the list contains two greatest numbers (as an example, last two list's elements are greatest numbers), the program crashes. I am sure my management of nodes' adresses is not correct.
EDIT: I was ment to say the "greatest" values just in case if the word "largest" mistakens.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
struct node* prev;
int value;
struct node* next;
} node;
node* allocateNode(int value);
node* addToEnd(node* head, int value);
node* makeList(node* head, int n);
node* deleteMaxElement(node* head);
void freeMemory(node* head);
int main()
{
node* head = NULL;
int n = 0;
printf("Enter number of elements: ");
if (!(scanf("%d", &n) == 1))
return 0;
head = makeList(head, n);
head = deleteMaxElement(head);
if (n > 1)
{
node* element = head;
printf("%d ", element->value);
while(element->next != NULL)
{
element = element->next;
printf("%d ", element->value);
}
printf("\n");
freeMemory(head);
}
return 0;
}
node* makeList(node* head, int n)
{
int value = 0;
if (n == 0)
return head;
printf("Enter value of 1 node: ");
if (scanf("%d", &value) == 1)
{
head = allocateNode(value);
for (int i = 1; i < n; i++)
{
printf("Enter value of %d node: ", i + 1);
if(scanf("%d", &value) == 1)
head = addToEnd(head, value);
}
}
return head;
}
node* allocateNode(int value)
{
node* newNode = (node*)malloc(sizeof(node));
newNode->prev = NULL;
newNode->next = NULL;
newNode->value = value;
return newNode;
}
node* addToEnd(node* head, int value)
{
node* newNode = allocateNode(value);
node* element = head;
while (element->next != NULL)
element = element->next;
element->next = newNode;
newNode->prev = element;
return head;
}
node* deleteMaxElement(node* head)
{
int max = head->value;
node* element = head;
// finds max element in list
while (element->next != NULL)
{
element = element->next;
if (element->value > max)
max = element->value;
}
// max element is in the list head
int firstElementDeleted = 0;
if (head->value == max)
{
node* temp = head->next;
free(head);
head = temp;
firstElementDeleted = 1;
}
// max elements is not in the list head
element = head;
while (element->next != NULL)
{
node* temp = NULL;
if (element->value == max)
{
if (!firstElementDeleted)
(element->prev)->next = element->next;
else
head = element->next;
temp = element->next;
free(element);
element = temp;
continue;
}
element = element->next;
}
// max elements is in the last node
if (element->value == max)
{
(element->prev)->next = NULL;
free(element);
}
return head;
}
void freeMemory(node* head)
{
node* next;
while (head != NULL)
{
next = head->next;
free(head);
head = next;
}
}

Previous pointer points to nowhere
You do not set the previous node pointer of the next element when you delete the element in the deleteMaxElement function. Add this one line to your function and it should work as intended. ;)
while (element->next != NULL)
{
node* temp = NULL;
if (element->value == max)
{
if (!firstElementDeleted) {
(element->prev)->next = element->next;
(element->next)->prev = element->prev;
}
else
head = element->next;
temp = element->next;
free(element);
element = temp;
continue;
}
element = element->next;
}

Related

delete the biggest number in linked list from anywhere (in C)

I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
int x;
struct Node *next;
} Node;
void deallocate(Node **root)
{
Node *curr = *root;
while (curr != NULL)
{
Node *aux = curr;
curr = curr->next;
free(aux);
}
*root = NULL;
}
void insert_end(Node **root, int value)
{
Node *new_node = malloc(sizeof(Node));
if (new_node == NULL)
{
exit(1);
}
new_node->next = NULL;
new_node->x = value;
if (*root == NULL)
{
*root = new_node;
return;
}
Node *curr = *root;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = new_node;
}
void deserialize(Node **root)
{
FILE *file = fopen("duom.txt", "r");
if (file == NULL)
{
exit(2);
}
int val;
while (fscanf(file, "%d, ", &val) > 0)
{
insert_end(root, val);
}
fclose(file);
}
int largestElement(struct Node *root)
{
int max = INT_MIN;
while (root != NULL)
{
if (max < root->x)
max = root->x;
root = root->next;
}
return max;
}
void deleteN(Node **head, int position)
{
Node *temp;
Node *prev;
temp = *head;
prev = *head;
for (int i = 0; i < position; i++)
{
if (i == 0 && position == 1)
{
*head = (*head)->next;
free(temp);
}
else
{
if (i == position - 1 && temp)
{
prev->next = temp->next;
free(temp);
}
else
{
prev = temp;
// Position was greater than
// number of nodes in the list
if (prev == NULL)
break;
temp = temp->next;
}
}
}
}
int main()
{
Node *root = NULL;
printf("MENU:\n");
printf("if you press 0 the list will be created \n");
printf("if you press 1 the list will be printed on a screen\n");
printf("if you press 2 it deletes the biggest element\n");
printf("if you press 3 the program ends\n\n");
int meniu;
printf("press:\n");
scanf("%d", &meniu);
while (meniu != 3)
{
if (meniu == 0)
{
deserialize(&root);
printf("sarasas sukurtas.\n");
}
if (meniu == 1)
{
for (Node *curr = root; curr != NULL; curr = curr->next)
printf("%d\n", curr->x);
}
if (meniu == 2)
{
int max_element = largestElement(root);
printf("%d max\n", max_element);
deleteN(&root, max_element);
}
printf("press:\n");
scanf("%d", &meniu);
}
deallocate(&root);
return 0;
}
When I compile and run the delete function it only deletes the biggest number first time and if I call it second time it deletes the last number of the list. Can someone help me fix that?
I edited it so all of the code can be seen because it was hard to understand it like I had it before
Your largestElement returns the largest data value in the list.
However, here:
int max_element = largestElement(root);
printf("%d max\n",max_element);
deleteN(&root, max_element);
you use the return value as if it is the position of the node with the largest element.
Instead of largestElement you need a function that returns the position of the element with the largest data value.
It would look something like:
int positionOfLargestElement(struct Node* root)
{
int pos = 0;
int maxpos = 0;
int max = INT_MIN;
while (root != NULL) {
++pos;
if (max < root->x)
{
max = root->x;
maxpos = pos;
}
root = root->next;
}
return maxpos;
}
note: The exact code depends a bit on whether the first node is considered to be position 0 or position 1 but the principle is the same.

Multiple data inside a single linked list node

Is it possible to have multiple data inside a single linked list node in C? And how do you input and access data with this?
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
char name[30];
struct node *next;
};
struct node *head, *tail = NULL;
void addNode(int data, char string) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->name[30] = string;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
void sortList() {
struct node *current = head, *index = NULL;
int temp;
if(head == NULL) {
return;
}
else {
while(current != NULL) {
index = current->next;
while(index != NULL) {
if(current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
void display() {
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
while(current != NULL) {
printf("%d - %s", current->data, current->name);
current = current->next;
}
printf("\n");
}
int main()
{
char string1[10] = "Aaron";
char string2[10] = "Baron";
char string3[10] = "Carla";
addNode(9, string1);
addNode(7, string2);
addNode(2, string3);
printf("Original list: \n");
display();
sortList();
printf("Sorted list: \n");
display();
return 0;
}
I don't understand why my code didn't work. I was trying to make use of single linked list where it can accept/input and print/output the number and the name at the same time.
What I want it to happen is to print the number and the name.
The output should be:
Carla - 2
Baron - 7
Aaron - 9
Please read my comments marked as // CHANGE HERE.
// CHANGE HERE: accept a character array as argument
void addNode(int data, char string[]) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
// CHANGE HERE: copy char array argument to name
strncpy(newNode->name, string, 30);
newNode->next = NULL;
if(head == NULL) {
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
void sortList() {
struct node *current = head, *index = NULL;
int temp;
char temp1[30];
if(head == NULL) {
return;
}
else {
while(current != NULL) {
index = current->next;
while(index != NULL) {
if(current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
// CHANGE HERE: swap the name along with data
strncpy(temp1, current->name, 30);
strncpy(current->name, index->name, 30);
strncpy(index->name, temp1, 30);
}
index = index->next;
}
current = current->next;
}
}
}
void display() {
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
while(current != NULL) {
printf("%d - %s\n", current->data, current->name);
current = current->next;
}
printf("\n");
}

double linked list with c

ok, now i have to make double linked list on c.
there are 7 functions which act on main.
append.
insertAt.
deleteAt.
print.
print_revers.
newnode.
newDLL.
i can amend only 5 functions
append, insertAt, deleteAt, print, print_reverse
finally i can make append,print,print_reverse
however, i can't make insertAt,deleteAt, because of index.
1. i can't understand why the code
else {
while (index-- >= 0) {
temp = temp->next;
}
make memory collide. for using index, i need to move node to collect position and connect to newnode. but it doesn't work...
2. also what's return; 's role? i have not seen such type of return.
3. how can i make deleteAt using index? i think deleteAt and insertAt have quiet similar algoritum. so i try to make insertAt first and deleteAt last. but what i write doesn't work well..
i can find a lot of data of doublelinkedlist on internet. but i can't find using index.... i have been listening c language lecture on only two month, so sorry about the spagettii code...
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *prev;
struct Node *next;
} Node;
typedef struct {
Node *head;
int size;
} DLL;
Node *newnode(int n)
{
Node *temp = (Node *)malloc(sizeof(Node));
temp->val = n;
temp->prev = NULL;
temp->next = NULL;
return temp;
}
DLL *newDLL() {
DLL *temp = (DLL *)malloc(sizeof(DLL));
temp->head = NULL;
temp->size = 0;
return temp;
}
void append(DLL *list, Node *newnode) {
struct Node* temp = list->head;
struct Node* newNode = newnode;
if (list->head == NULL) {
list->head = newNode;
list->size++;
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
list->size++;
temp->next = newNode;
newNode->prev = temp;
}
void insertAt(DLL *list, int index, Node *newnode) {
struct Node* temp = (Node *)malloc(sizeof(Node));
if (index < 0 || index >= list->size + 1) {
printf("out of range\n");
}
else if (index == 0) {
newnode->next = list->head;
list->head->prev = newnode;
list->head = newnode;
}
else {
while (index-- >= 0) {
temp = temp->next;
}
temp->val = newnode->val;
temp->next = list->head->next;
list->head->next = temp;
temp->prev = list->head;
if (temp->next != NULL)
temp->next->prev = temp;
}
}
void deleteAt(DLL *list, int index) {
//save reference to first link
struct Node* temp = (Node *)malloc(sizeof(Node));
//if only one link
if (list->head->next == NULL) {
list->head->prev = NULL;
}
else {
list->head->next->prev = NULL;
}
list->head = list->head->next;
//return the deleted link
return;
}
void print(DLL *list) {
struct Node* temp = list->head;
printf("Forward: ");
while (temp != NULL) {
printf("[%d] ", temp->val);
temp = temp->next;
}
printf("\n");
}
void print_reverse(DLL *list) {
struct Node* temp = list->head;
if (temp == NULL) return; // empty list, exit
// Going to last Node
while (temp->next != NULL) {
temp = temp->next;
}
// Traversing backward using prev pointer
printf("Reverse: ");
while (temp != NULL) {
printf("[%d] ", temp->val);
temp = temp->prev;
}
printf("\n");
}
int main() {
DLL *list = newDLL();
int i;
for (i = 1; i < 6; i++) {
append(list, newnode(i));
}
print(list);
deleteAt(list, -1);
deleteAt(list, 5);
deleteAt(list, 0);
print(list);
deleteAt(list, 2);
print(list);
deleteAt(list, 2);
print(list);
insertAt(list, -1, newnode(6));
insertAt(list, 3, newnode(6));
insertAt(list, 0, newnode(7));
print(list);
insertAt(list, 1, newnode(8));
print(list);
insertAt(list, 4, newnode(9));
print(list);
print_reverse(list);
return 0;
}
The part where you insert at index has problems:
temp = malloc is wrong, it should start with temp = head.
in the insertion:
temp->val = newnode->val;
temp->next = list->head->next;
list->head->next = temp;
temp->prev = list->head;
temp->next should not be head->next, it should be newnode. newnode->next should be temp->next etc.

Saving pointer to last node in doubly linked list when performing insertion sort

Here I have a header file to include functions:
#ifndef driver_h
#define driver_h
#include <stdio.h>
#include <stdlib.h>
typedef struct node node;
typedef struct nodePtrs nodePtrs;
struct node {
node* next;
node* prev;
int data;
};
void sortedInsert(node** top, node* newNode, node** last) {
node* current;
if (*top == NULL) {
*top = newNode;
} else if ((*top)->data >= newNode->data) {
newNode->next = *top;
newNode->next->prev = newNode;
*top = newNode;
if ((*top)->next == NULL) {
*last = *top;
}
} else {
current = *top;
while (current->next != NULL &&
current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
if (current->next != NULL) {
newNode->next->prev = newNode;
}
current->next = newNode;
newNode->prev = current;
}
if ((*top)->next == NULL) {
*last = *top;
}
}
void insertionSort(node** top, node** last) {
node* sorted = NULL;
node* current = *top;
while (current != NULL) {
node* next = current->next;
current->prev = current->next = NULL;
sortedInsert(&sorted, current, last);
current = next;
}
*top = sorted;
}
node* deleteByPos(node* list, node** last, int position) {
int c = 0;
node* temp;
node* prev;
temp=list;
if (temp==NULL) {
printf("No nodes available to delete\n\n");
return list;
} else {
while(temp!=NULL && c != position) {
prev=temp;
temp=temp->next;
c++;
}
if (temp==NULL) {
printf("Reached end of list, position not available\n\n");
return list;
} else if (temp->next == NULL) {
prev->next=temp->next;
*last = prev;
free(temp);
return list;
} else {
prev->next=temp->next;
temp->next->prev = prev;
free(temp);
return list;
}
}
}
node* makeNode(int n) {
node* np = malloc(sizeof (node));
np->data = n;
np->prev = NULL;
np->next = NULL;
return np;
}
void printList(node* np) {
while (np != NULL) {
printf("%d\n", np->data);
np = np->next;
}
}
void printListReverse(node* np) {
while (np != NULL) {
printf("%d\n", np->data);
np = np->prev;
}
}
#endif /* driver_h */
and a main file:
#include "driver.h"
int main() {
int n;
node* np;
node* top;
node* last;
printf("Enter integers to add to list\n");
do {
if (scanf("%d", &n) != 1) {
n = 0;
}
if (n != 0) {
np = makeNode(n);
if (top == NULL) {
top = np;
} else {
last->next = np;
np->prev = last;
}
last = np;
}
} while (n != 0);
printf("\n\n");
printf("You entered:\n");
printList(top);
printf("\n\n");
printf("In reverse:\n");
printListReverse(last);
printf("\n\n");
printf("Enter a position to delete:");
scanf("%d", &n);
top = deleteByPos(top, &last, n);
printf("\n\n");
printf("In reverse after delete:\n");
printListReverse(last);
insertionSort(&top, &last);
printf("From top after sort:\n");
printList(top);
printf("In reverse after Sort:\n");
printListReverse(last);
}
What this program does is take user input of integers, stores them in a doubly linked list, deletes a node at a user defined point and then performs an insertion sort. What I am trying to do is save a pointer to the last node in the sortedInsert function with the following code:
if ((*top)->next == NULL) {
*last = *top;
}
However, if you enter 6 5 3 1 9 8 4 2 7 4 2, then delete at position 2, when printing in reverse it prints out 6 5 4 4 2 2 1. For some reason it skips over 9 7 8. I cannot figure out why or how to fix this. How can I do this properly?
With lists, it helps to draw a diagram for all the cases. It's natural to use induction on lists to prove your code is correct.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h> /* Asserting is useful when it come to lists especially. */
struct node {
struct node* next;
struct node* prev;
int data;
};
/* Saves you from dealing with 'top' and 'tail' every time. */
struct list {
struct node *head, *tail;
};
/* https://en.wikipedia.org/wiki/Insertion_sort */
void insertionSort(struct list* list) {
struct node* i = list->head, *j0, *j1;
while(i) {
j1 = i, j0 = j1->prev;
while(j0 && j0->data > j1->data) {
/* Swap. */
int temp = j0->data;
j0->data = j1->data;
j1->data = temp;
/* Decrement. */
j1 = j0;
j0 = j0->prev;
}
i = i->next;
}
}
/* Returns whether the position was deleted. */
int deleteByPos(struct list* list, int position) {
struct node* n;
assert(list);
/* Node n is the position's in the list. */
for(n = list->head; n && position; n = n->next, position--);
if (n==NULL) {
printf("No nodes available to delete\n\n");
return 0;
}
/* Fixme: If I'm not mistaken, there are 9 cases for you to be
mathematically certain this works, and I haven't tried them all.
Eg, 1 node, 2 nodes x2, 3 nodes x3, where the internal node is the 2nd of
the 3 nodes. */
if(n->prev == NULL) {
/* The first one. */
assert(list->head == n);
list->head = n->next;
if(n->next) n->next->prev = NULL;
} else {
/* Skip over. */
n->prev->next = n->next;
}
if(n->next == NULL) {
/* The last one. */
assert(list->tail == n);
list->tail = n->prev;
if(n->prev) n->prev->next = NULL;
} else {
/* Skip over. */
n->next->prev = n->prev;
}
n->prev = n->next = NULL; /* Helps in debugging. */
free(n);
return 1;
}
struct node* makeNode(struct list *list, int n) {
struct node* np = malloc(sizeof *np);
if(!np) return 0;
np->data = n;
np->prev = list->tail;
np->next = NULL;
/* Push it in the list. */
if(list->tail) {
assert(list->head != NULL && list->tail->next == NULL);
list->tail->next = np;
} else {
/* The first one. */
assert(list->head == NULL && list->tail == NULL);
list->head = np;
}
list->tail = np;
return np;
}
void printList(const struct list*const list) {
const struct node *n = list->head;
while (n) {
printf("%d\n", n->data);
n = n->next;
}
}
void printListReverse(const struct list*const list) {
const struct node *n = list->tail;
while (n) {
printf("%d\n", n->data);
n = n->prev;
}
}
int main(void) {
int n;
struct list list = { 0, 0 };
printf("Enter integers to add to list\n");
while(scanf("%d", &n) == 1 && n)
if(!makeNode(&list, n)) return perror("node"), EXIT_FAILURE;
printf("\n\n");
printf("You entered:\n");
printList(&list);
printf("\n\n");
printf("In reverse:\n");
printListReverse(&list);
printf("\n\n");
printf("Enter a position to delete:");
scanf("%d", &n);
printf("You entered %d.\n", n);
deleteByPos(&list, n);
printf("\n\n");
printf("In reverse after delete:\n");
printListReverse(&list);
insertionSort(&list);
printf("From top after sort:\n");
printList(&list);
printf("In reverse after Sort:\n");
printListReverse(&list);
return EXIT_SUCCESS;
}
*One would ideally free memory on exit.
It is usually much simpler to use a sentinel node rather than NULL to indicate the end of a list. So an empty list consists of a node whose head and tail point to itself. Once you add elements, sentinel->next is the first in the list and sentinel->prev is the last in the list. This removes many of the cases you have to test for NULL in your code:
#ifndef driver_h
#define driver_h
#include <stdio.h>
#include <stdlib.h>
typedef struct node node;
typedef struct nodePtrs nodePtrs;
struct node {
node* next;
node* prev;
int data;
};
void sortedInsert(node* top, node* newNode) {
node* current = top;
while (current->next != top &&
current->next->data < newNode->data) {
current = current->next;
}
newNode->next = current->next;
newNode->next->prev = newNode;
current->next = newNode;
current->next->prev = current;
}
void insertionSort(node* top) {
node* current = top->next;
// make top an empty ring so can append to it
top->next = top->prev = top;
while (current != top) {
node* next = current->next;
sortedInsert(top, current);
current = next;
}
}
node* deleteByPos(node* top,int position) {
int c = 0;
node* temp = top->next;
while (true) {
if (temp == top) {
printf("Reached end of list, position not available\n\n");
return top;
}
if (c == position) {
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
free(temp);
return top;
}
temp = temp->next;
c++;
}
}
node* makeNode(int n) {
node* np = malloc(sizeof(node));
np->data = n;
np->prev = np;
np->next = np;
return np;
}
void printList(node* top) {
for (node* np = top->next; np != top; np = np->next) {
printf("%d\n", np->data);
}
}
void printListReverse(node* top) {
for (node* np = top->prev; np != top; np = np->prev) {
printf("%d\n", np->data);
}
}
#endif /* driver_h */
main file :
#include "driver.h"
int main() {
int n;
node* np;
node* top;
top= makeNode(0);
printf("Enter integers to add to list\n");
do {
if (scanf_s("%d", &n) != 1) {
n = 0;
}
if (n != 0) {
np = makeNode(n);
np->prev = top->prev;
top->prev = np;
top->prev->next = top;
np->prev->next = np;
}
} while (n != 0);

Segregating even and odd nodes in a Linked List

I need to segregate even and odd nodes in a Linked List in C.
Example:
Original list: 3,1,8,2,5,6
After change: 8,2,6,3,1,5
I have a problem when the head list data is an odd number, it is cutting out the even numbers.
Example:
Original list: 3,1,8,2,5,6
After change: 3,1,5
typedef struct Node {
int data; // store information
struct Node * next; //referance to the next node
}Node;
Node * create(Node * L, int value)
{
Node *current = L ,* new_node = (Node*)malloc(sizeof(Node)); // create and allocate a node
new_node->data = value;
new_node->next = NULL;
if (L == NULL)
{
L = new_node;
current = new_node;
}
else
{
while (current->next != NULL)
current = current->next;
current->next = new_node;
current = new_node;
}
return L;
}
Node * Change_Even_Odd(Node * L)
{
Node *oddhead = NULL, *evenhead = NULL, *lastodd = NULL, *lasteven = NULL, *current = L;
while (current != NULL)
{
// if current is even node
if (current->data % 2 == 0)
{
if (evenhead == NULL)
{
evenhead = current;
lasteven = current;
}
else
{
lasteven->next = current; // to connect the node to the list in the end
lasteven = current; // final list
}
}
else
{
// if current is odd node
if (oddhead == NULL)
{
oddhead = current;
lastodd = current;
}
else
{
lastodd->next = current;
lastodd = current;
}
}
current = current->next;
}
if (evenhead != NULL) // to put the even node in the head list
L = evenhead;
if (lasteven != NULL) // link the odd nodes to the even nodes
lasteven->next = oddhead;
if (lastodd != NULL) //end of list
lastodd->next = NULL;
return L;
}
void Print_List(Node * head)
{
while (head != NULL)
{
printf("%4d", head->data);
head = head->next;
}
}
int main()
{
Node * list = NULL; //empty linked list
srand(time(NULL));
int i, size = rand() % 10 + 1;
for (i = 0; i < size; i++)
list = create(list, rand() % 10 + 1);
printf("%d\n",size);
Print_List(list);
printf("\n");
Change_Even_Odd(list);
Print_List(list);
printf("\n");
}
Change_Even_Odd(list); should be list = Change_Even_Odd(list); (I already pointed out.)
– BLUEPIXY

Resources