C - linked list removing values on insertion - c

I'm trying to create a method that lets me insert a new node in my liked list at a chosen index,
it is currently working as intended when inserting into index 0 or 1 but when I try to insert into any index >= 2 the first value in the list is being lost. any ideas why?
example main:
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
int main( void ) {
List list = new_list();
add(list, "Three");
add(list, "Two");
add(list, "Zero");
print_list(list);
printf("Inserting at 1 \n");
insert_at(list, 1, "one")
print_list(list);
printf("Inserting at 2 \n");
insert_at(list, 2, "inserted")
print_list(list);
header file:
typedef struct Node{
char *value;
struct Node *next;
}Node;
typedef Node** List;
List new_list();
Node *new_node(char *value);
void add(List list,char *value);
int is_empty(List list);
void print_list(const List list);
int insert_at(List list,int index,char *value);
method file:
#include <stdlib.h>
#include <stdio.h>
#include "list.h"
#include <string.h>
List new_list(){
List list = malloc(sizeof(List));
*list = NULL;
return list;
}
Node *new_node(char *value){
Node *node = malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
void add(List list,char *value){
if (*list == NULL){
*list = new_node(value);
}else {
Node *node = new_node(value);
node->next = *list;
*list = node;
}
}
int is_empty(List list){
if (*list == NULL){
return 1;
} return 0;
}
void print_list(const List list){
printf("[");
Node *curr = *list;
if (curr == NULL){
printf("]\n");
return;
}
while (curr->next != NULL){
printf("\"%s\", ", curr->value );
curr = curr->next;
}
printf("\"%s\"", curr->value );
printf("]\n");
}
int insert_at(List list,int index,char *value){
if ((index > 0 && is_empty(list) == 1) || index < 0){
return 0;
}
int i= 0;
if (index == 0){
add(list, value);
return 1;
}
while((*list) != NULL){
//advancing loop
i++;
//checking if wanted index = lists index
if (i == index){
//creating new node
Node *node = new_node(value);
//updating next values;
node->next = (*list)->next;
(*list)->next = node;
return 1;
}
(*list) =(*list)->next;
}
return 0;
}
example output:
["Zero", "Two", "Three"]
Inserting at 1
["Zero", "One", "Two", "Three"]
Inserting at 2
["One", "INSERTED", "Two", "Three"]

In this while loop
while((*list) != NULL){
//advancing loop
i++;
//checking if wanted index = lists index
if (i == index){
//creating new node
Node *node = new_node(value);
//updating next values;
node->next = (*list)->next;
(*list)->next = node;
return 1;
}
(*list) =(*list)->next;
}
the statement
(*list) =(*list)->next;
overwrites the pointer to the head node that results at least in numerous memory leaks.
And the second function parameter should have an unsigned integer type as for example size_t.
Also the function new_list should look at least like
List new_list(){
List list = malloc(sizeof( *list ));
*list = NULL;
return list;
}
In general it is a bad approach with using such a typedef
typedef Node** List;
It only confuses readers of the code.

Related

Trouble compiling .c and header files with gcc in Ubuntu WSL

I am trying to compile some c code with multithreading and for some reason I'm getting a segmentation fault in the Ubuntu WSL terminal when I try to run:
gcc -o mashu concurrent_list.c concurrent_list.h
The files I am trying to run are the following:
concurrent_list.c:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "concurrent_list.h"
struct node {
int value;
node* next;
pthread_mutex_t* lock;
// add more fields
};
struct list {
// add fields
node* head;
pthread_mutex_t* lock;
};
void print_node(node* node)
{
// DO NOT DELETE
if(node)
{
printf("%d ", node->value);
}
}
list* create_list()
{
// add code here
list* l = malloc(sizeof(list));
if(l == NULL){
printf("malloc error");
}
l->head = NULL;
l->head->next = NULL;
if(pthread_mutex_init(l->lock, NULL) != 0){
printf("mutex init failed\n");
}
if(pthread_mutex_init(l->head->lock, NULL) != 0){
printf("mutex init failed\n");
}
return l;
}
void delete_list(list* list)
{
// add code here
pthread_mutex_lock(list->lock);
node* head = list->head;
node* next = head->next;
while(next->next != NULL){
free(head);
next = next->next;
head = next;
}
pthread_mutex_unlock(list->lock);
free(list);
}
void insert_value(list* list, int value)
{
// add code here
// if the list is empty
pthread_mutex_lock(list->lock);
if(list->head == NULL){
list->head->value = value;
pthread_mutex_unlock(list->lock);
}
else{
// init newnode
node* newNode = malloc(sizeof(node));
if(!newNode){
printf("malloc failed\n");
}
newNode->value = value;
newNode->next = NULL;
if(pthread_mutex_init(newNode->lock, NULL) != 0){
printf("mutex init failed\n");
}
node* curr = list->head;
// lock the list and the first node
pthread_mutex_lock(curr->lock);
if(curr->next == NULL){ // first and only node at the start of a list
if(curr->value > value){ // insert the newnode at the beggining
list->head = newNode;
newNode->next = curr;
}else{
curr->next = newNode;
}
pthread_mutex_unlock(list->lock);
pthread_mutex_unlock(curr->lock);
// finished the insert
}
else{
node* prev = curr;
curr = curr->next;
pthread_mutex_unlock(list->lock);
pthread_mutex_lock(curr->lock);
while(curr->value < value && curr->next != NULL){
pthread_mutex_unlock(prev->lock);
prev = curr;
curr = curr->next;
pthread_mutex_lock(curr->lock);
}
if(curr->next == NULL){
curr->next = newNode;
}else{
prev->next = newNode;
newNode->next = curr;
}
pthread_mutex_unlock(prev->lock);
pthread_mutex_unlock(curr->lock);
}
}
}
void remove_value(list* list, int value)
{
// add code here
}
void print_list(list* list)
{
// add code here
node* curr = list->head;
pthread_mutex_lock(list->lock);
if(curr != NULL){
pthread_mutex_unlock(list->lock);
while(curr != NULL){
pthread_mutex_lock(curr->lock);
print_node(curr);
curr = curr->next;
pthread_mutex_unlock(curr->lock);
}
}
printf("\n"); // DO NOT DELETE
}
void count_list(list* list, int (*predicate)(int))
{
int count = 0; // DO NOT DELETE
// add code here
printf("%d items were counted\n", count); // DO NOT DELETE
}
int main(){
list* l = create_list();
printf("1\n");
insert_value(l,6);
printf("2\n");
insert_value(l,12);
insert_value(l,3);
insert_value(l,19);
insert_value(l,8);
printf("3\n");
print_list(l);
printf("4\n");
delete_list(l);
}
concurrent_list.h:
typedef struct node node;
typedef struct list list;
list* create_list();
void delete_list(list* list);
void print_list(list* list);
void insert_value(list* list, int value);
void remove_value(list* list, int value);
void count_list(list* list, int (*predicate)(int));
The thrown error when compiling is:
Segmentation fault
Am I accessing illegal memory, not compiling correctly or am I using mutex threads wrong?
Any help would be appriciated.
create_list():
l->head = NULL will segfault if malloc failed. You probably want to return NULL; in addition to the print.
l->head->next = NULL; will always segfault as you set l->head to NULL
pthread_mutex_init(l->head->lock, NULL) will always segfault as l->head is NULL.
insert_value():
list->head->value = value; will segfault if list->head is NULL. You even ensure that it is with the if statement.
As you lock the list on modification (and you need to do that at least for the head changes) I eliminated the node lock. Inlined print_node() in print_list() as the former required caller to take a lock which is risky. Fixed create_list() per above. Simplified delete_list(). Fixed (per above) and simplified insert_value(). Removed dead code remove_value():
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct node node;
struct node {
int value;
node *next;
};
typedef struct list list;
struct list {
node *head;
pthread_mutex_t *lock;
};
list* create_list();
void delete_list(list* list);
list *insert_value(list* list, int value);
void print_list(list* list);
list* create_list() {
list* l = malloc(sizeof(*l));
if(!l) {
printf("malloc error");
return NULL;
}
l->head = NULL;
if(pthread_mutex_init(l->lock, NULL) != 0) {
printf("mutex init failed\n");
}
return l;
}
void delete_list(list *l) {
pthread_mutex_lock(l->lock);
while(l->head) {
node *n = l->head;
l->head = l->head->next;
free(n);
}
free(l);
pthread_mutex_unlock(l->lock);
}
list *insert_value(list *l, int value) {
node* newNode = malloc(sizeof(node));
if(!newNode){
printf("malloc failed\n");
return NULL;
}
newNode->value = value;
// head
pthread_mutex_lock(l->lock);
if(!l->head || value < l->head->value){
newNode->next = l->head;
l->head = newNode;
pthread_mutex_unlock(l->lock);
return l;
}
// non-head
node *n = l->head;
for(; n->next && value >= n->next->value; n = n->next);
newNode->next = n->next;
n->next = newNode;
pthread_mutex_unlock(l->lock);
return l;
}
void print_list(list *l) {
pthread_mutex_lock(l->lock);
for(node *n = l->head; n; n = n->next) {
printf("%d ", n->value);
}
pthread_mutex_unlock(l->lock);
printf("\n");
}
int main(){
list* l = create_list();
printf("1\n");
insert_value(l, 6);
printf("2\n");
insert_value(l,12);
insert_value(l,3);
insert_value(l,19);
insert_value(l,8);
printf("3\n");
print_list(l);
printf("4\n");
delete_list(l);
}
and the output is:
1
2
3
3 6 8 12 19
4

Inserting Element single linked List C

I try to insert an Element in an empty single Linked List and print that.
The code looks like this.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node{
int val;
struct Node* next;
}ll;
void addElement(ll* List, int num){
ll* new = malloc(sizeof(ll));
if(new == NULL){
printf("NO MEMORY\n");
exit(0);
}
new->val = num;
new->next = NULL;
if(List == NULL){
List = new;
return;
}
ll* curr = List;
while(curr->next != NULL){
curr = curr->next;
}
curr->next = new;
}
void printElements(ll* List){
ll* curr = List;
while(curr != NULL){
printf("%i\n", curr->val);
curr = curr->next;
}
}
*int main(){
ll* list = NULL;
addElement(list, 20);
addElement(list, 30);
addElement(list, 19);
printElements(list);
return 0;*
}
Does anybody see my mistake? Because it only works if i already have an Element in my List and nothing will be printed.
The function deals with a copy of the value of the pointer to the head node used as the function argument.
void addElement(ll* List, int num){
So this statement
List = new;
does not change the value of the original pointer. It changes the value of the copy of the original pointer.
The function can be defined the following way
int addElement( ll **List, int num )
{
ll *new_node = malloc( sizeof( ll ) );
int success = new_node != NULL;
if ( success )
{
new_node->val = num;
new_node->next = NULL;
while ( *List != NULL ) List = &( *List )->next;
*List = new_node;
}
return success;
}
And the function is called like
ll* list = NULL;
addElement( &list, 20);
addElement( &list, 30);
addElement( &list, 19);

Polynominal with doubly linked list - pointer problem

I made some polynomial code with a doubly-linked list. for example, if
you write 1 and 2 then 1 is a degree and 2 is coefficient. 1x^2 insert
to doubly linked list. the problem is that when I check my code, the Node
head->degree is changing. if I write 1x^2 then head->degree is 1 next,
I write 2x^1 then head-> degree should maintain 1 but head-> degree
change to 2 I think there is some problem in the head pointer.
#include <stdio.h>
#include <stdlib.h>
// struct
struct Node {
int degree;
int coefficient;
struct Node* next;
struct Node* prev;
};
// global variables
int de; // degree
int co; // coefficient
int flag;
Node** head = (Node**)malloc(sizeof(Node)); //
Node** head1 = (Node**)malloc(sizeof(Node)); //
Node** head2 = (Node**)malloc(sizeof(Node)); //
Node** head3 = (Node**)malloc(sizeof(Node)); //
Node* newNode = (Node*)malloc(sizeof(Node)); //
// function
Node* inputpoly(void);
void printNode(Node* inp);
Node* multiply(Node* a, Node* b);
// main
int main() {
// head null
(*head1) = NULL;
(*head2) = NULL;
(*head3) = NULL;
while (1) {
printf("Input (degree) (coefficient) : ");
scanf_s("%d %d", &de, &co);
if (de * co < 0) { continue; }
if (de < 0 && co < 0) {
printf("Done!\n");
break;
}
*head = inputpoly();
}
printNode(*head);
//multiply(*head1, *head2);
free(head1);
free(head2);
free(head3);
free(newNode);
free(head);
}
Node* inputpoly(void) {
// create Node
newNode->degree = de;
newNode->coefficient = co;
newNode->next = NULL;
newNode->prev = NULL;
// case1
if (flag == 0) {
// list
if ((*head1) == NULL) {
*head1 = newNode;
}
// list x
else {
Node* horse = (*head1);
// front of head
// ------------------There is some problem
printf("%d\n", 1);
printf("--%d\n", newNode->degree);
printf("--%d\n", horse->degree);
if (horse->degree > newNode->degree) {
newNode->next = horse;
horse->prev = newNode;
*head1 = newNode;
}
// barward of head
else {
int num = 0;
while (horse->next != NULL) {
horse = horse->next;
if (horse->degree > newNode->degree) {
horse->prev->next = newNode;
newNode->next = horse;
newNode->prev = horse->prev;
horse->prev = newNode;
num = 1;
break;
}
}
// behind tail
if (num == 0) {
horse->next = newNode;
newNode->prev = horse;
}
}
}
return *head1;
}
}
void printNode(Node* inp) {
Node* horse = inp;
if (horse == NULL)
{
return;
}
while (horse != NULL) {
if (horse->prev == NULL) {
if (horse->degree == 1) {
printf("%d", horse->coefficient);
}
else {
printf("%d x^%d", horse->coefficient, horse->degree);
}
}
else {
if (horse->degree == 1) {
printf(" + %d", horse->coefficient);
}
else {
printf(" + %d x^%d", horse->coefficient, horse->degree);
}
}
}
printf("\n");
}
"i think there is some head pointer problem, and if I fixed it I can this problem. so I want to maintain this code as possible. I want some
advice or solution to my head pointer"
The code posted in your example does not compile:
Before you can fix a head pointer problem the code must compile. This list of errors is detailing 2 things:
first, functions cannot be called outside of a function, eg:
Node** head = (Node**)malloc(sizeof(Node)); //
Node** head1 = (Node**)malloc(sizeof(Node)); //
Node** head2 = (Node**)malloc(sizeof(Node)); //
Node** head3 = (Node**)malloc(sizeof(Node)); //
Node* newNode = (Node*)malloc(sizeof(Node)); //
should be called from within main(void){...} or some other function.
second, every occurrence of Node should be prepended with struct. eg:
struct Node** head = malloc(sizeof(struct Node *));
(have also removed the cast, and modified the size of what you are creating memory for, i.e. a pointer)
Rather then fix these and other problems, here is an example of a doubly linked list that can demonstrate the structure of a simple working program. You can adapt the following to match your needs:
struct Node {
int deg;
int coef;
struct Node* next; // Pointer to next node in DLL
struct Node* prev; // Pointer to previous node in DLL
};
void inputpoly(struct Node** head_ref, int deg, int coef)
{
//allocate node
struct Node *new_node = malloc(sizeof(*new_node));
//assign data
new_node->deg = deg;
new_node->coef = coef;
//set next as new head and prev to null
new_node->next = (*head_ref);
new_node->prev = NULL;
//change prev of head to new */
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
//point head to the new node */
(*head_ref) = new_node;
}
void printList(struct Node* node)
{
struct Node* last;
printf("\nread forward\n");
while (node != NULL) {
printf(" %d,%d ", node->deg,node->coef);
last = node;
node = node->next;
}
printf("\nread reverse\n");
while (last != NULL) {
printf(" %d,%d ", last->deg,last->coef);
last = last->prev;
}
}
int main(void)
{
//start with empty list
struct Node* head = NULL;
//create and populate new nodes
inputpoly(&head, 7, 2);
inputpoly(&head, 1, 4);
inputpoly(&head, 4, 6);
//ouput list
printList(head);
getchar();
return 0;
}
Note that this code is offered as a basic demonstration of creating doubly linked list, and illustrate how to traverse both directions. Because it does not free allocated memory, it is not recommended that it be used for any production purpose without addressing that omission.

How to delete nodes of a linked list between two indices?

I have the following linked list implementation:
struct _node {
char *string;
struct _node *next;
}
struct _list {
struct _node *head;
struct _node *tail;
}
I want to make the following function:
void deleteList(struct _list *list, int from, int to) {
int i;
assert(list != NULL);
// I skipped error checking for out of range parameters for brevity of code
for (i = from; i <= to; i++) {
deleteNode(list->head, i);
}
}
// I ran this function with this linked list: [First]->[Second]->NULL
like this deleteNodes(list, 1, 1) to delete the second line and got
[First]->[Second]->NULL but when I run it like this deleteList(list, 0, 1) with this input [First]->[Second]->[Third]->NULL I get a seg fault.
Here is my deleteNode function
void deleteNode(struct _node *head, int index) {
if (head == NULL) {
return;
}
int i;
struct _node *temp = head;
if (index == 0) {
if (head->next == NULL) {
return;
}
else {
head = head->next;
free(head);
return;
}
}
for (i = 0; temp!=NULL && i<index-1; i++) {
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
return;
}
Link next = temp->next->next;
free(temp->next);
temp->next = next;
}
I wrote a separate function to delete the head of the linked list if from or to = 0:
void pop(struct _node *head) {
if (head == NULL) {
return;
}
struct _node *temp = head;
head = head->next;
free(temp);
}
but it gives me seg fault or memory error Abort trapL 6.
It's all good to use just one struct, a node for your purpose.
struct node {
char *string;
struct node *next;
};
Then your loop for removing elements between two indices will not delete the right elements if you don't adjust the index according to the changing length of the list. And you must also return the new head of the list.
struct node *deleteList(struct node *head, unsigned from, unsigned to) {
unsigned i;
unsigned count = 0;
for (i = from; i <= to; i++) {
head = delete_at_index(head, i - count);
count++;
}
return head;
}
The help function delete_at_index looks as follows.
struct node *delete_at_index(struct node *head, unsigned i) {
struct node *next;
if (head == NULL)
return head;
next = head->next;
return i == 0
? (free(head), next) /* If i == 0, the first element needs to die. Do it. */
: (head->next = delete_at_index(next, i -
1), head); /* If it isn't the first element, we recursively check the rest. */
}
Complete program below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char *string;
struct node *next;
};
void freeList(struct node *head) {
struct node *tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp->string);
free(tmp);
}
}
struct node *delete_at_index(struct node *head, unsigned i) {
struct node *next;
if (head == NULL)
return head;
next = head->next;
return i == 0
? (free(head), next) /* If i == 0, the first element needs to die. Do it. */
: (head->next = delete_at_index(next, i -
1), head); /* If it isn't the first element, we recursively check the rest. */
}
struct node *deleteList(struct node *head, unsigned from, unsigned to) {
unsigned i;
unsigned count = 0;
for (i = from; i <= to; i++) {
head = delete_at_index(head, i - count);
count++;
}
return head;
}
void pushvar1(struct node **head_ref, char *new_data) {
struct node *new_node = malloc(sizeof(struct node));
new_node->string = strdup(new_data);
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printListvar1(struct node *node) {
while (node != NULL) {
printf(" %s ", node->string);
node = node->next;
}
printf("\n");
}
int main(int argc, char **argv) {
struct node *head = NULL;
for (int i = 0; i < 5; i++) {
char str[2];
sprintf(str, "node%d", i);
pushvar1(&head, str);
}
puts("Created Linked List: ");
printListvar1(head);
head = deleteList(head, 0, 2);
puts("Linked list after deleted nodes from index 0 to index 2: ");
printListvar1(head);
freeList(head);
return 0;
}
Test
Created Linked List:
node4 node3 node2 node1 node0
Linked list after deleted nodes from index 0 to index 2:
node1 node0
every programming problem can be solved by adding an extra level of indirection: use a pointer to pointer ...
unsigned deletefromto(struct node **head, unsigned from, unsigned to)
{
unsigned pos,ret;
struct node *this;
for (pos=ret=0; this = *head;pos++) {
if (pos < from) { head = &(*head)->next; continue; }
if (pos > to) break;
*head = this->next;
free(this);
ret++;
}
return ret; /* nuber of deleted nodes */
}

How to Delete the last element in a linked list in C?

I don't know how to delete the first and last element in a linked list in c. Below is my program, that uses a linked list. I have no idea how to actually delete the last element but I am able to find it. the element consists of an integer and the next pointer. if someone could please help me, it would be much appreciated.
struct ListNode{
int value;
struct ListNode *next;
};
typedef struct ListNode Link;
void deleteLast(Link *);
void printList(Link *);
void deleteFirst(Link *);
int main(){
Link *myList;
Link *curr, *newlink;
int i;
curr = myList;
for(i = 0; i < 10; i++){
newlink = (Link*) malloc(1*sizeof(Link));
newlink->value = i*i;
curr->next = newlink;
curr = newlink;
}
curr->next = NULL;
curr = myList->next;
deleteFirst(curr);
printList(curr);
printf("\n");
}
void deleteLast(Link *head)
{
Link *curr;
curr = head->next;
while (curr->next!=NULL)
{
curr = curr->next;
}
free(curr->next);
curr->next = NULL;
}
void printList(Link *head){
Link *curr;
curr = head->next;
printf("[");
if(curr!=NULL){
printf("%d",curr->value);
curr = curr->next;
}
while(curr != NULL){
printf(", %d", curr->value);
curr = curr->next;
}
printf("]\n");
}
void deleteFirst(Link *head){
Link *curr;
curr = head->next;
free(curr->value);
free(curr->next);
printf("%d\t",curr->value);
}
Nothing I try works, please can you help me.
You have many errors in your code.
When you create your list:
You don't have to cast the return value of malloc
You are doing curr->next = newlink; where curr = myList with initialized value. You can change your loop to
Link *myList = NULL;
Link *curr, *newlink;
int i;
curr = myList;
for(i = 0; i < 10; i++){
newlink = malloc(1*sizeof(Link));
newlink->value = i*i;
if (curr != NULL)
curr->next = newlink;
else
myList = newlink;
curr = newlink;
}
When you remove the last element you are going to far, that's why it's not working
Link *curr;
curr = head->next;
while (curr->next != NULL) {
head = curr;
curr = curr->next;
}
free(head->next);
head->next = NULL;
When you want to remove the first element of your list
You don't have to free the field value since you have not allocated it with malloc
Even if you remove the first element of your list, you are not changing the value of the begining of your list in the main. It's why you must take as a param a Link**
void deleteFirst(Link **head){
Link *curr;
curr = (*head)->next;
free(*head);
*head = curr;
}
And you can call this function from the main by giving the address of the beginning of your list:
deleteFirst(&myList);
deleteLast(myList);
printList(myList);
of course in all your functions you must check if you have at least some values in the list and not an empty pointer NULL
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct node Node;
struct node{
int element;
Node *next;
};
Node* head = NULL;
bool put(int data)
{
bool retVal = false;
Node* temp;
do
{
if (head == NULL)
{
head = malloc(sizeof(Node));
if (head)
{
printf("New head created\n");
head->element = data;
head->next = NULL;
printf("Element %d stored\n", data);
retVal = true;
break;
}
else
{
printf("Could not create new head\n");
break;
}
}
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = malloc(sizeof(Node));
temp->next->element = data;
temp->next->next = NULL;
printf("Element %d stored\n", data);
retVal = true;
break;
} while(1);
return retVal;
}
bool get(int *pData)
{
bool retVal = false;
Node* temp;
if (head != NULL)
{
retVal = true;
Node *prevNode = head;
temp = prevNode;
while (temp->next)
{
prevNode = temp;
temp = temp->next;
}
*pData = temp->element;
printf("Element %d retrieved\n", *pData);
free(temp);
printf("Node freed\n");
if (temp == head)
{
head = NULL;
}
else
{
prevNode->next = NULL;
}
}
return retVal;
}
int main(void)
{
int retrievedNum;
int num;
for (num = 0; num < 5; num++)
{
put(num);
}
printf("\n");
for (num = 0; num < 6; num++)
{
get(&retrievedNum);
}
put(num);
get(&retrievedNum);
printf("Element retrieved: %d\n", retrievedNum);
return 1;
}
This code will work for deleting last element in linklist:
void dellast()
{
r=head;
struct node* z;
do
{
z=r;
r=r->next;
if(r->next==NULL)
{
z->next=NULL;
free(r->next);
}
}while(z->next!=NULL);
}
The Code works like this:
Keep the track of current node and its previous node.
If current->next==NULL means it is the last node.
So do previous->next=NULL and free the current node
I've made my own (singly) LinkedList example in C, its proven to work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/********** GLOBALS *******************************/
#define OK 0
#define ERROR -1
/********** STRUCT AND TYPES DEFINTIONS ***********/
/* a node with key, data and reference to next node*/
typedef struct Node {
int key;
char string[1024];
struct Node *next; // pointer to next node
} Node;
/* the actual linked list: ref to first and last Node, size attribute */
typedef struct LinkedList {
struct Node *first;
struct Node *last;
int size;
} LinkedList;
/********** FUNCTION HEADERS **********************/
LinkedList* init_list();
void insert_end(LinkedList *list, int key, char string[]);
void insert_beginning(LinkedList *list, int key, char string[]);
int remove_end(LinkedList *list);
int remove_beginning(LinkedList *list);
int print_list(LinkedList *list);
void free_list(LinkedList *list);
char * get_string(LinkedList *list, int key);
/*********** FUNCTION DEFINITIONS ***************/
/**
* init_list Returns an appropriately (for an empty list) initialized struct List
*
* #return LinkedList * ..ptr to the newly initialized list
*/
LinkedList * init_list() {
printf("initializing list...\n");
LinkedList *list = (LinkedList*) malloc(sizeof(LinkedList));
list->first = NULL;
list->last = NULL;
list->size = 0;
return list;
}
/**
* Given a List, a key and a string adds a Node containing this
* information at the end of the list
*
* #param list LinkedList * ..ptr to LinkedList
* #param key int .. key of the Node to be inserted
* #param string char[] .. the string of the Node to be inserted
*/
void insert_end(LinkedList *list, int key, char string[]) {
printf("----------------------\n");
list->size++; // increment size of list
// intialize the new Node
Node* newN = (Node*) malloc(sizeof(Node));
newN->key = key;
strcpy(newN->string, string);
newN->next = NULL;
Node* oldLast = list->last; // get the old last
oldLast->next = newN; // make new Node the next Node for oldlast
list->last = newN; // set the new last in the list
printf("new Node(%p) at end: %d '%s' %p \n", newN, newN->key, newN->string,newN->next);
}
/**
* Given a List, a key and a string adds a Node, containing
* this information at the beginning of the list
*
* #param list LinkedList * ..ptr to LinkedList
* #param key int .. key of the Node to be inserted
* #param string char[] .. the string of the Node to be inserted
*/
void insert_beginning(LinkedList *list, int key, char string[]) {
printf("----------------------\n");
list->size++; // increment size of list
Node* oldFirst = list->first; //get the old first node
/* intialize the new Node */
Node* newN = (Node*) malloc(sizeof(Node));
newN->key = key;
strcpy(newN->string, string);
newN->next = oldFirst;
list->first = newN; // set the new first
/* special case: if list size == 1, then this new one is also the last one */
if (list->size == 1)
list->last = newN;
printf("new Node(%p) at beginning: %d '%s' %p \n", newN, newN->key,newN->string, newN->next);
}
/**
* Removes the first Node from the list
*
* #param list LinkedList * .. ptr to the List
*
* #return OK | ERROR
*/
int remove_beginning(LinkedList *list) {
printf("----------------------\n");
if (list->size <= 0)
return ERROR;
list->size--;
Node * oldFirst = list->first;
printf("delete Node(%p) at beginning: '%d' '%s' '%p' \n", oldFirst,oldFirst->key, oldFirst->string, oldFirst->next);
free(list->first); //free it
list->first = oldFirst->next;
oldFirst = NULL;
return OK;
}
/**
* Removes the last Node from the list.
*
* #param list LinkedList * .. ptr to the List
*
* #return OK | ERROR
*/
int remove_end(LinkedList *list) {
printf("----------------------\n");
/* special case #1 */
if (list->size <= 0)
return ERROR;
/* special case #2 */
if (list->size == 1) {
free(list->first);
list->first = NULL;
list->last = NULL;
return OK;
}
printf("delete Node(%p) at end: '%d' '%s' '%p' \n", list->last,list->last->key, list->last->string, list->last->next);
list->size--; // decrement list size
Node * startNode = list->first;
/* find the new last node (the one before the old last one); list->size >= 2 at this point!*/
Node * newLast = startNode;
while (newLast->next->next != NULL) {
newLast = newLast->next;
}
free(newLast->next); //free it
newLast->next = NULL; //set to NULL to denote new end of list
list->last = newLast; // set the new list->last
return OK;
}
/**
* Given a List prints all key/string pairs contained in the list to
* the screen
*
* #param list LinkedList * .. ptr to the List
*
* #return OK | ERROR
*/
int print_list(LinkedList *list) {
printf("----------------------\n");
if (list->size <= 0)
return ERROR;
printf("List.size = %d \n", list->size);
Node *startN = list->first; //get first
/* iterate through list and print contents */
do {
printf("Node#%d.string = '%s', .next = '%p' \n", startN->key,startN->string, startN->next);
startN = startN->next;
} while (startN != NULL);
return OK;
}
/**
* Given a List, frees all memory associated with this list.
*
* #param list LinkedList * ..ptr to the list
*/
void free_list(LinkedList *list) {
printf("----------------------\n");
printf("freeing list...\n");
if (list != NULL && list->size > 0) {
Node * startN = list->first;
Node * temp = list->first;
do {
free(temp);
startN = startN->next;
temp = startN;
} while (startN != NULL);
free(list);
}
}
/**
* Given a List and a key, iterates through the whole List and returns
* the string of the first node which contains the key
*
* #param list LinkedList * ..ptr to the list
* #param key int .. the key of the Node to get the String from
*
* #return OK | ERROR
*/
char * get_string(LinkedList *list, int key) {
printf("----------------------\n");
Node *startN = list->first; //get first
/* iterate through list and find Node where node->key == key */
while (startN->next != NULL) {
if (startN->key == key)
return startN->string;
else
startN = startN->next;
}
return NULL;
}
/*************** MAIN **************/
int main(void) {
LinkedList *list = init_list();
insert_beginning(list, 1, "im the first");
insert_end(list, 2, "im the second");
insert_end(list, 3, "im the third");
insert_end(list, 4, "forth here");
print_list(list);
remove_end(list);
print_list(list);
remove_beginning(list);
print_list(list);
remove_end(list);
print_list(list);
printf("string at node with key %d = '%s' \n",2,get_string(list, 2));
free_list(list);
return OK;
}
Hope this implementation example helps.

Resources