Segmentation fault using doubly linked list in C - c

I've written an implementation of a doubly linked list with a .h prototype here and everything runs fine until I start entering values in the terminal. I get a segmentation fault after entering the second value, but, if I just use 1 value it executes normally. I've gone through it several times, but, I can't find my mistake. Could you guys help me find why I'm getting the error?
Here's the .h file:
#include <stdio.h>
typedef struct node Node;
struct node
{
int d;
Node *link;
}*head,*current,*prev;
int num_nodes;
void linked_list_init(int data);
void linked_list_sort();
void linked_list_print();
And here's the .c file:
#include "link.h"
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main(){
int n,e,i;
printf("How many numbers do you want to sort: ");
scanf("%d",&e);
for(i=0;i<e;i++){
printf("Enter number: ");
scanf("%d",&n);
linked_list_init(n);
}
linked_list_sort();
printf("The sorted numbers are: ");
linked_list_print();
}
void linked_list_init(int data){
Node *prev=0,*next=0;
current=(Node*)malloc(sizeof(Node));
if(head==0)
{
head=current;
current->d=data;
current->link=0;
prev=current;
}
else{
current->d=data;
current->link=0;
prev->link=current;
prev=current;
}
}
void linked_list_sort(){
int i,j;
Node *prev=0,*next=0;
current=head;
prev=head;
next=head->link;
for(i=0;i<num_nodes-1;i++)
{
for(j=0;j<num_nodes-i-1;j++)
{
if(current->d>next->d)
{
current->link=next->link;
next->link=current;
if(current==head)
{
head=next;prev=next;
}
else
{
prev->link=next;prev=next;
}
if(next!=0) //check whether final node is reached
next=current->link;
}
else //move each node pointer by one position
{
prev=current;
current=next;
next=current->link;
}
}
//next iteration
current=head;
prev=head;
next=current->link;
}
}
void linked_list_print(){
current=head;
while(current!=0){
printf("%d ",current->d);
current=current->link;
}
}

The problem is that you're masking the global variables with local declarations in your function. That means that the variable prev in the functions are not the same as the global variable prev.
Aside from that, you should never place variable definitions in header files, as those will clash with each other if the header file is included in multiple files.
There is also another small bug, in that you don't increase the counter when inserting a new node into the list.

There is no need to initialize head to 0 because in your case you have declared it globally in header file ( although its not a good practice to declare variables in header files). The problem here is you are redefining prev node in void linked_list_init(int data) function. Just delete the prev node from there and everything would work fine.
Tips:
-> Declare the head, prev, current nodes in .c file.
-> Use NULL instead of 0 or even you can use (void *) 0 instead of simply 0

It seems like you are creating and initializing *prev and *current everytime the linked_list_init function is called. Hence after you enter the second value, the second if loop is using prev, which has actually been set to 0.
I think what you are trying to do is use the *prev, *head and *current as global variables (since you have declared them in your header file). Just use extern to declare them in the source file and things should work.

The global variable used in your program are uninitialized and hence prone to garbage values . Also i suggest the following defination for your node
struct node {
int d;
node *llink; // Left Link
node *rlink; // Right Link
};
typedef struct node* Node;
Node head = NULL; // Head node
Also
void linked_list_init(int data) {
Node newnode = (Node) malloc(sizeof (Node));
newnode->d = data;
Node curr;
if (head == NULL) {
newnode->llink = NULL;
newnode->rlink = NULL;
head = newnode;
} else {
curr = head;
while (curr->rlink) {
curr = curr->rlink;
}
curr->rlink = newnode;
newnode->rlink = NULL;
newnode->llink = curr;
}
}
The above will keep adding elements to the end of the list .
You can print data out easily as follows :
void linked_list_print() {
Node curr;
curr = head;
while (curr) {
printf("Element Data : %d", curr->d);
curr = curr->rlink;
}
}

Related

how to remove code duplications in this code?

I am a new C99 programmer and want the help of the community on this one.
I wrote the following function which receives two pointers for a node (Or simply Node) and a pointer to a pointer to node (Or *Node) an merges them together into one sorted Node.
This is Given:
typedef struct node_t {
int x;
struct node_t *next;
} *Node;
typedef enum {
SUCCESS = 0,MEMORY_ERROR, EMPTY_LIST, UNSORTED_LIST, NULL_ARGUMENT,
} ErrorCode;
int getListLength(Node list);
bool isListSorted(Node list);
This is the code I wrote:
ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out)
{
if (merged_out==NULL)
return NULL_ARGUMENT;
if (list1==NULL || list2==NULL)
return EMPTY_LIST;
if (!isListSorted(list1) || !isListSorted(list2))
return UNSORTED_LIST;
Node ptr=*merged_out;
int list1_len=getListLength(list1),list2_len=getListLength(list2);
for (int i=0;i<list1_len+list2_len;i++)
{
int min=0;
if (list1!=NULL && (list2==NULL || (list2!=NULL && list1->x<=list2->x))){
min = list1->x;
list1=list1->next;
}
else{
min=list2->x;
list2=list2->next;
}
ptr->x=min;
if (i==list1_len+list2_len-1){
ptr->next=NULL;//The next for the last Node should be Null
continue;
}
ptr->next=malloc(sizeof(*ptr));
if (ptr->next==NULL){
//We should Free all previosly allocated memory
//except for the first node since it was not allocated via malloc
return MEMORY_ERROR;
}
ptr=ptr->next;
}
ptr=NULL;
return SUCCESS;
}
But after reviewing my code I was told it has a lot of code duplications (more precisely inside he for loop) which should be corrected by using external functions, do u notice any code duplications? and how to fix that, any ideas?

Print first element of linked list in C lang

While teaching my self how to manage linked lists in C i came across some difficulties. I created a function getNode to create a list of 4 integers. Now i would like to printf the first element of the list, so that i can learn something new. Unfortunatelly, when i try to recall the head node of the list, the program prints the last node. When all code was in main() , there was no problems or what so ever, only when i got to factorize the code the dificulities mentioned have occured. It might be just lacking a pointer, or some sort of logical error. Any help apreciated! thanks
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct list
{
int x;
struct list *next;
}list;
list *getNode()
{
int marker = 0;
int base;
list *head, *current;
head=current=NULL;
while (marker < 4)
{
printf("wprowdz liczbe dla NodE o markerze: %d \n", marker + 1);
scanf("%d", &base);
list *node = malloc(sizeof(list));
node->x = base;
node->next = NULL;
if (head == NULL)
{
current = head = node;
}
else
{
current = current->next = node;
}
marker++;
}
return current;
}
void printNode(list *head)
{
printf("this shoud print the first element of linked list :");
printf("%d", head->x);
}
int main()
{
list *start = getNode();
printNode(start);
}
My dear friend, in the function getNode you need to return the head pointer not the current pointer. The head pointer points at the first node but the current node is pointing at the last node because you are updating the current node everytime while loop is executed.
So, we need to return the head pointer in order to traverse through the linked list or print the first element. Hope you get it !! Cheers, feel free to ask questions

Making of linked list by head and node

here's my code in C for making of linked list. Its giving runtime error after the while loop gets executed for one time. Plz help me in correcting my code. (totally confused that where's the error.) I am making a head node first and then adding child nodes to it.
#include <stdio.h>
#include <stdlib.h>
typedef struct node nd;
typedef nd *link;
struct node{
int data;
link next;
};
typedef struct {
int size;
link head;
}list;
void create(link temp)
{
link new;
new=(link)malloc(sizeof(nd));
printf("enter data: ");
scanf("%d",new->data);
temp->next=new;
temp=temp->next;
}
list createlist()
{
list sl;
sl.size=0;
sl.head=0;
return sl;
}
int main()
{
list sl;
sl=createlist();
link temp;
temp=sl.head;
char c;
while (1)
{
printf("Add node?: ");
scanf(" %c",&c);
if (c=='y')
{
create(temp);
sl.size++;
}
else
break;
}
return 0;
}
your createlist() function is returning a reference to a local variable that goes out of scope after it returns. You should instead return a heap based value:
list* createlist() {
list* sl = (list*)malloc(sizeof(list));
sl->size=0;
sl->head=0;
return sl;
}
Initially temp points to NULL. temp = sl.head;
In create(temp) temp->next = new;
You are dereferencing a NULL, address 0x0. I get a segmentation fault when I do that.
Need to change the algorithm.
A debugger shows this problem immediately.
You could use a pointer to pointer for temp. It would be easier to read if you didn't use a typedef for a pointer to node. I haven't tested this, but it should be close:
nd ** create(nd **temp)
{
nd *new;
new=(nd *)malloc(sizeof(nd)); /* this cast shouldn't be needed */
printf("enter data: ");
scanf("%d",&(new->data));
new->next = NULL;
*temp = new;
return &(new->next);
}
/* ... */
int main()
{
nd **temp;
temp = &(sl.head);
/* ... */
temp = create(temp);
/* ... */
}

Trouble with insertion of C string into linked list

I am writing a program to read a file and then store the data into a linked List.
linkedList.h
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
struct linked_list
{
char *stock_name;
double stock_price;
struct linked_list *next;
};
typedef struct linked_list NODE;
NODE* insert(NODE *head, double stock_price, char *stock_name);
void printList(NODE *head);
linkedList.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include"linkedList.h"
void printList(NODE *head)
{
NODE *this = head;
while(this != NULL)
{
printf("stock name:%s , stock price:%lf\n", this->stock_name, this->stock_price);
this = this->next;
}
}
NODE* insert(NODE *head, double stock_price, char *stock_name)
{
NODE *newNode = malloc(sizeof(NODE));
if(head == NULL)
{
newNode->stock_price = stock_price;
newNode->stock_name = stock_name;
head = newNode;
}
else
{
newNode->stock_price = stock_price;
newNode->stock_name = stock_name;
newNode->next = head;
head = newNode;
}
return head;
}
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "linkedList.h"
NODE *head;
bool headNode = true;
void insertIntoLinkedList(char *stock_name, double stock_price);
int main ( int argc, char *argv[] )
{
head = malloc(sizeof(NODE));
double stock_price;
char stock_name[100];
int stock_name_counter = 0;
**..then I read the file..**
stock_name[stock_name_counter] = '\0'; //to end my C string
stock_name_counter = 0; //this is used for reading char
insertIntoLinkedList(stock_name, stock_price); //I double checked here,the name and price is correct
**......**
printList(head); //**Not the output I want**
fclose( file );
void insertIntoLinkedList(char *m_stock_name, double m_stock_price)
{
if(headNode == true)
{
head = insert(NULL, m_stock_price, m_stock_name);
headNode = false; //this is used to insert data to my linked list for the first time
}
else
{
head = insert(head, m_stock_price, m_stock_name);
}
}
Here is the problem: if the file contains:
YAHOO 120
GOOGLE 10
APPLE 199
my printList() gave me this:
APPLE 120
APPLE 10
APPLE 199
I have been trying to debug for hours and still cannot figure why the name is not stored in my linked list properly(but the price is store properly..)...any help will be appreciate :)
The address of stock_name in main is always constant through out the program and you store that address to newNode->stock_name and so you will always get the last stored string in stock_name.
Modification
NODE* insert(NODE *head, double stock_price, char *stock_name)
{
NODE *newNode = malloc(sizeof(NODE));
newNode->stock_name = malloc(strlen(stock_name)+1);
if(head == NULL)
{
newNode->stock_price = stock_price;
strcpy(newNode->stock_name, stock_name);
head = newNode;
}
else
{
newNode->stock_price = stock_price;
strcpy(newNode->stock_name, stock_name);
newNode->next = head;
head = newNode;
}
return head;
}
Don't forget to free the allocated memory.
You need to make a copy of the string stored in stock_name when you call insert. As is, all the nodes point to the same buffer, and every time you read a new line, you overwrite the buffer. In the end, this means that all of the nodes have the text APPLE because that's the last content that's read into the shared buffer. If you either copy the buffer's contents (instead of just the pointer to the buffer) or allocate a new buffer every time you read from the file, this will be fixed.
Your basic problem is that C does not have a "String" type. A string is simple an array of characters, and an array "decays" to a pointer when used as an argument to a function. Based on the way you're using it, your insert() function should do a second malloc() to allocate storage for the string and use strdup() or similar to store it.
Your other problem is that you've got a logic flaw in the insert() function. You aren't initializing newNode->next if head is NULL. You should be doing newNode->next = head either way. If it's NULL, good. Your list tail will then not be pointing at an indeterminate place.

How to implement a linked list in C?

I am creating a linked list as in the previous question I asked. I have found that the best way to develop the linked list is to have the head and tail in another structure. My products struct will be nested inside this structure. And I should be passing the list to the function for adding and deleting. I find this concept confusing.
I have implemented the initialize, add, and clean_up. However, I am not sure that I have done that correctly.
When I add a product to the list I declare some memory using calloc. But I am thinking shouldn't I be declaring the memory for the product instead. I am really confused about this adding.
Many thanks for any suggestions,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRODUCT_NAME_LEN 128
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
struct product_data_t *next;
}product_data_t;
typedef struct list
{
product_data_t *head;
product_data_t *tail;
}list_t;
void add(list_t *list, int code, char name[], int cost);
void initialize(list_t *list);
void clean_up(list_t *list);
int main(void)
{
list_t *list = NULL;
initialize(list);
add(list, 10, "Dell Inspiron", 1500);
clean_up(list);
getchar();
return 0;
}
void add(list_t *list, int code, char name[], int cost)
{
// Allocate memory for the new product
list = calloc(1, sizeof(list_t));
if(!list)
{
fprintf(stderr, "Cannot allocated memory");
exit(1);
}
if(list)
{
// First item to add to the list
list->head->product_code = code;
list->head->product_cost = cost;
strncpy(list->head->product_name, name, sizeof(list->head->product_name));
// Terminate the string
list->head->product_name[127] = '/0';
}
}
// Initialize linked list
void initialize(list_t *list)
{
// Set list node to null
list = NULL;
list = NULL;
}
// Release all resources
void clean_up(list_t *list)
{
list_t *temp = NULL;
while(list)
{
temp = list->head;
list->head = list->head->next;
free(temp);
}
list = NULL;
list = NULL;
temp = NULL;
}
============================== Edited ============================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRODUCT_NAME_LEN 64
// typedef struct product_data product_data_t;
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
}product_data_t;
typedef struct list
{
struct list *head;
struct list *tail;
struct list *next;
struct list *current_node;
product_data_t *data;
}list_t;
void add(list_t *list, int code, char name[], int cost);
int main(void)
{
list_t *list = NULL;
list = initialize(list);
add(list, 1001, "Dell Inspiron 2.66", 1299);
add(list, 1002, "Macbook Pro 2.66", 1499);
clean_up(list);
getchar();
return 0;
}
void add(list_t *list, int code, char name[], int cost)
{
/* Allocate memory for the new product */
product_data_t *product = (product_data_t*) calloc(1, sizeof(*product));
if(!product)
{
fprintf(stderr, "Cannot allocate memory.");
exit(1);
}
/* This is the first item in the list */
product->product_code = code;
product->product_cost = cost;
strncpy(product->product_name, name, sizeof(product->product_name));
product->product_name[PRODUCT_NAME_LEN - 1] = '\0';
if(!list->head)
{
/* Assign the address of the product. */
list = (list_t*) product;
/* Set the head and tail to this product */
list->head = (list_t*) product;
list->tail = (list_t*) product;
}
else
{
/* Append to the tail of the list. */
list->tail->next = (list_t*) product;
list->tail = (list_t*) product;
}
/* Assign the address of the product to the data on the list. */
list->data = (list_t*) product;
}
If you are looking to better understand the basics of linked lists, take a look at the following document:
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf
Arguably you want your list data structure to be external to the data that it stores.
Say you have:
struct Whatever
{
int x_;
}
Then your list structure would look like this:
struct Whatever_Node
{
Whatever_Node* next_
Whatever* data_
}
Ryan Oberoi commented similarly, but w/o example.
In your case the head and tail could simply point to the beginning and end of a linked-list. With a singly linked-list, only the head is really needed. At it's most basic, a linked-list can be made by using just a struct like:
typedef struct listnode
{
//some data
struct listnode *next;
}listnodeT;
listnodeT *list;
listnodeT *current_node;
list = (listnodeT*)malloc(sizeof(listnodeT));
current_node = list;
and as long as list is always pointing to the beginning of the list and the last item has next set to NULL, you're fine and can use current_node to traverse the list. But sometimes to make traversing the list easier and to store any other data about the list, a head and tail token are used, and wrapped into their own structure, like you have done. So then your add and initialize functions would be something like (minus error detection)
// Initialize linked list
void initialize(list_t *list)
{
list->head = NULL;
list->tail = NULL;
}
void add(list_t *list, int code, char name[], int cost)
{
// set up the new node
product_data_t *node = (product_data_t*)malloc(sizeof(product_data_t));
node->code = code;
node->cost = cost;
strncpy(node->product_name, name, sizeof(node->product_name));
node->next = NULL;
if(list->head == NULL){ // if this is the first node, gotta point head to it
list->head = node;
list->tail = node; // for the first node, head and tail point to the same node
}else{
tail->next = node; // append the node
tail = node; // point the tail at the end
}
}
In this case, since it's a singly linked-list, the tail is only really useful for appending items to the list. To insert an item, you'll have to traverse the list starting at the head. Where the tail really comes in handy is with a doubly-linked list, it allows you to traverse the list starting at either end. You can traverse this list like
// return a pointer to element with product code
product_data_t* seek(list_t *list, int code){
product_data_t* iter = list->head;
while(iter != NULL)
if(iter->code == code)
return iter;
iter = iter->next;
}
return NULL; // element with code doesn't exist
}
Often times, the head and tail are fully constructed nodes themselves used as a sentinel to denote the beginning and end of a list. They don't store data themselves (well rather, their data represent a sentinel token), they are just place holders for the front and back. This can make it easier to code some algorithms dealing with linked lists at the expense of having to have two extra elements. Overall, linked lists are flexible data structures with several ways to implement them.
oh yeah, and nik is right, playing with linked-lists are a great way to get good with pointers and indirection. And they are also a great way to practice recursion too! After you have gotten good with linked-list, try building a tree next and use recursion to walk the tree.
I am not writing the code here but you need to do the following:
Create and object of list, this will remain global for the length of program.
Malloc the size of product _ data _ t.
For first element (head is NULL), point head to the malloced' address.
To add next element, move to the end of list and then add the pointer of malloced address to next of last element. (The next of the last element will always be NULL, so thats how you traverse to end.)
Forget tail for a while.
If you are learning C pointer theory this is a good exercise.
Otherwise, it feels like too much indirection for code that is not generic (as in a library).
Instead of allocating a static 128 byte character string, you might want to do some more pointer practice and use an allocated exact length string that you clean up at exit.
Academically, kungfucraigs' structure looks more generic then the one you have defined.
You're calloc'ing space for your list_t struct, just pointers to list head and tail, which isn't what you want to do.
When you add to a linked list, allocate space for an actual node in the list, which is your product_data_t struct.
You're allocating the wrong chunk of memory. Instead of allocating memory for each list element, you're allocating for the list head and tail.
For simplicity, get rid of the separate structure for the head and tail. Make them global variables (the same scope they're in now) and change them to be listhead and listtail. This will make the code much more readable (you won't be needlessly going through a separate structure) and you won't make the mistake of allocating for the wrong struct.
You don't need a tail pointer unless you're going to make a doubly linked list. Its not a major element to add once you create a linked list, but not necessary either.
In memory your items are linked by pointers in the list structure
item1 -> item2
Why not make the list structure part of your item?
Then you allocate a product item, and the list structure is within it.
typedef struct product_data
{
int product_code;
char product_name[PRODUCT_NAME_LEN];
int product_cost;
struct list_t list; // contains the pointers to other product data in the list
}product_data_t;
I think u first need to Imagin back-end. Code are nothing to important. Go here and visualize back-end basic c code of all insertion.
1) Insertion at beginning Visit and scroll to get every instruction execution on back- end
And u need front and imagin Go here
Back end imagin
And All other possible insertion here.
And important thing u can use this way.
struct Node{
int data;//data field
struct Node*next;//pointer field
};
struct Node*head,*tail; // try this way
or short cut
struct Node{
int data;//data field
struct Node*next;//pointer field
}*head,*tail; //global root pointer
And << Click >> To visualize other linked list problem.
Thanks.
A demo for Singly Linked List. If you prefer, try to check Circular Linked List and Doubly Linked List.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;
// Iterating over a list
void
print_list(node_t *head)
{
node_t *current = head;
while(current != NULL)
{
printf("%d\n", current->val);
current = current->next;
}
}
// Adding an item to the end of the list
void
push_end(node_t *head, int val)
{
node_t *current = head;
while (current->next != NULL)
{
current = current->next;
}
current->next = malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
// Adding an item to the head of the list
void
push_head(node_t **head, int val)
{
node_t *new_node = NULL;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
// Removing the head item of the list
int
pop_head(node_t **head)
{
int retval = -1;
node_t *next_node = NULL;
if (*head == NULL) {
return -1;
}
next_node = (*head)->next;
retval = (*head)->val;
free(*head);
*head = next_node;
return retval;
}
// Removing the last item of the list
int
pop_last(node_t *head)
{
int retval = 0;
node_t *current = NULL;
if (head->next == NULL) {
retval = head->val;
free(head);
return retval;
}
/* get to the second to last node in the list */
current = head;
while (current->next->next != NULL) {
current = current->next;
}
/* now current points to the second to last item of the list.
so let's remove current->next */
retval = current->next->val;
free(current->next);
current->next = NULL;
return retval;
}
// Removing a specific item
int
remove_by_index(node_t **head, int n)
{
int i = 0;
int retval = -1;
node_t *current = *head;
node_t *temp_node = NULL;
if (n == 0) {
return pop_head(head);
}
for (i = 0; i < n - 1; i++) {
if (current->next == NULL) {
return -1;
}
current = current->next;
}
temp_node = current->next;
retval = temp_node->val;
current->next = temp_node->next;
free(temp_node);
return retval;
}
int
main(int argc, const char *argv[])
{
int i;
node_t * testnode;
for (i = 0; i < argc; i++)
{
push_head(&testnode, atoi(argv[i]));
}
print_list(testnode);
return 0;
}
// http://www.learn-c.org/en/Linked_lists
// https://www.geeksforgeeks.org/data-structures/linked-list/
The linked list implementation inspired by the implementation used in the Linux kernel:
// for 'offsetof', see: https://stackoverflow.com/q/6433339/5447906.
#include <stddef.h>
// See: https://stackoverflow.com/q/10269685/5447906.
#define CONTAINER_OF(ptr, type, member) \
( (type *) ((char *)(ptr) - offsetof(type, member)) )
// The macro can't be used for list head.
#define LIST_DATA(ptr, type, member) \
CONTAINER_OF(ptr, type, member);
// The struct is used for both: list head and list nodes.
typedef struct list_node
{
struct list_node *prev, *next;
}
list_node;
// List heads must be initialized by this function.
// Using the function for list nodes is not required.
static inline void list_head_init(list_node *node)
{
node->prev = node->next = node;
}
// The helper function, mustn't be used directly.
static inline void list_add_helper(list_node *prev, list_node *next, list_node *nnew)
{
next->prev = nnew;
nnew->next = next;
nnew->prev = prev;
prev->next = nnew;
}
// 'node' must be a list head or a part of a list.
// 'nnew' must not be a list head or a part of a list. It may
// be uninitialized or contain any data (even garbage).
static inline void list_add_after(list_node *node, list_node *nnew)
{
list_add_helper(node, node->next, nnew);
}
// 'node' must be a list head or a part of a list.
// 'nnew' must not be a list head or a part of a list. It may
// be uninitialized or contain any data (even garbage).
static inline void list_add_before(list_node *node, list_node *nnew)
{
list_add_helper(node->prev, node, nnew);
}
// 'node' must be part of a list.
static inline list_node *list_del(list_node *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
return node->prev;
}
Example of usage:
#include <stdio.h>
// The struct must contain 'list_node' to be able to be inserted to a list
typedef struct
{
int data;
list_node node;
}
my_struct;
// Convert 'list_node *' to 'my_struct*' that contains this 'list_node'
static inline my_struct* get_my_struct(list_node *node_ptr)
{
return LIST_DATA(node_ptr, my_struct, node);
}
void print_my_list(list_node *head)
{
printf("list: {");
for (list_node *cur = head->next; cur != head; cur = cur->next)
{
my_struct *my = get_my_struct(cur);
printf(" %d", my->data);
}
printf(" }\n");
}
// Print 'cmd' and run it. Note: newline is not printed.
#define TRACE(cmd) \
(printf("%s -> ", #cmd), (cmd))
int main()
{
// The head of the list and the list itself. It doesn't contain any data.
list_node head;
list_head_init(&head);
// The list's nodes, contain 'int' data in 'data' member of 'my_struct'
my_struct el1 = {1};
my_struct el2 = {2};
my_struct el3 = {3};
print_my_list(&head); // print initial state of the list (that is an empty list)
// Run commands and print their result.
TRACE( list_add_after (&head , &el1.node) ); print_my_list(&head);
TRACE( list_add_after (&head , &el2.node) ); print_my_list(&head);
TRACE( list_add_before(&el1.node, &el3.node) ); print_my_list(&head);
TRACE( list_del (head.prev) ); print_my_list(&head);
TRACE( list_add_before(&head , &el1.node) ); print_my_list(&head);
TRACE( list_del (&el3.node) ); print_my_list(&head);
return 0;
}
The result of execution of the code above:
list: { }
list_add_after (&head , &el1.node) -> list: { 1 }
list_add_after (&head , &el2.node) -> list: { 2 1 }
list_add_before(&el1.node, &el3.node) -> list: { 2 3 1 }
list_del (head.prev) -> list: { 2 3 }
list_add_before(&head , &el1.node) -> list: { 2 3 1 }
list_del (&el3.node) -> list: { 2 1 }
http://coliru.stacked-crooked.com/a/6e852a996fb42dc2
Of course in real life you will most probably use malloc for list elements.
In C language, we need to define a Node to store an integer data and a pointer to the next value.
struct Node{
int data;
struct Node *next;
};
To add a new node, we have a function add which has data as an int parameter. At first we create a new Node n. If the program does not create n then we print an error message and return with value -1. If we create the n then we set the data of n to have the data of the parameter and the next will contain the root as it has the top of the stack. After that, we set the root to reference the new node n.
#include <stdio.h>
struct node
{
int data;
struct node* next;
};
int main()
{
//create pointer node for every new element
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
//initialize every new pointer with same structure memory
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
head->data = 18;
head->next = second;
second->data = 20;
second->next = third;
third->data = 31;
third->next = NULL;
//print the linked list just increment by address
for (int i = 0; i < 3; ++i)
{
printf("%d\n",head->data++);
return 0;
}
}
This is a simple way to understand how does pointer work with the pointer. Here you need to just create pointer increment with new node so we can make it as an automatic.
Go STL route. Declaring linked lists should be agnostic of the data. If you really have to write it yourself, take a look at how it is implemented in STL or Boost.
You shouldn't even keep the *next pointer with your data structure. This allows you to use your product data structure in a various number of data structures - trees, arrays and queues.
Hope this info helps in your design decision.
Edit:
Since the post is tagged C, you have equivalent implementations using void* pointers that follow the basic design principle. For an example, check out:
Documentation | list.c | list.h

Resources