Pointers to structures - c

typedef struct queue {
int q[max];
int qhead;
int qrear;
} queue;
void init_queue(queue *QUEUE)
{
QUEUE.qhead = 0;
QUEUE.qrear = -1;
}
void enqueue(queue *QUEUE,int data)
{
QUEUE.qrear++;
QUEUE.q[QUEUE.qrear] = data;
}
int process_queue(queue *QUEUE)
{
if(QUEUE.qhead > QUEUE.qrear)
return -1;
else
return QUEUE.q[QUEUE.qhead++];
}
I am implementing queues using arrays just to keep it simple. Wats the error with the above code?

First of all, the . operator is used to access members of a struct. You need -> to access members of a pointer to a struct:
void init_queue(queue *QUEUE)
{
QUEUE->qhead = 0;
QUEUE->qrear = -1;
}
Just as a tid-bit, a->b is equivalent to (*a).b - that is, first dereferencing the pointer a, and then accessing a member of that struct.

Besides the compilation error from using . instead of ->, you also have potential buffer overflow in enqueue; you'll overflow your buffer after max calls. You have a couple of choice depending on what you want.
1) You can turn this into a circular queue:
void enqueue(queue *QUEUE,int data)
{
QUEUE->qrear = (QUEUE->qrear + 1) % max;
QUEUE->q[QUEUE->qrear] = data;
}
2) You can stop adding once you hit max:
void enqueue(queue *QUEUE,int data)
{
if (QUEUE->qrear < (max - 1))
{
QUEUE->qrear++;
QUEUE->q[QUEUE->qrear] = data;
}
}

You should use -> instead of .:
Accessing structs' values using pointers is done using QUEUE-> or (*QUEUE). and not QUEUE.. You first need to dereference the pointer and only then access the value.
typedef struct queue {
int q[max];
int qhead;
int qrear;
} queue;
void init_queue(queue *QUEUE)
{
QUEUE->qhead = 0;
QUEUE->qrear = -1;
}
void enqueue(queue *QUEUE,int data)
{
QUEUE->qrear++;
QUEUE->q[QUEUE->qrear] = data;
}
int process_queue(queue *QUEUE)
{
if(QUEUE->qhead > QUEUE->qrear)
return -1;
else
return QUEUE->q[QUEUE->qhead++];
}

Related

Manipulation of stack with full usage of pointers and arrays

I was given this code from Uni and I am trying to do operations with it , the push function ask for two pointers and I could not figure out how can I pass the data to the item part.I have tried using another structure containing the data but I failed. I am stuck at the end of the code and I would like to learn how to push data using this code. How can I proceed ?
It would be preferable if the data itself was stored in a structur.
Thanks in advance.
typedef struct stk
{
struct stk* elems[MAX]; int top;
} stack, *stackptr;
void Init(stack* s)
{
s->top = 0;
}
int IsEmpty(stack s)
{
return (s.top == 0);
}
void Push(struct stk* item, stack* s)
{
if (s->top == MAX)
printf("Stack voll!");
s->elems[s->top] = item;
s->top++;
}
struct stk* Pop(stack* s)
{
if (IsEmpty(*s)) return NULL;
s->top--;
return s->elems[s->top];
}
int main()
{
stack* ptr = (stackptr)malloc(sizeof(stack));
Init(ptr);
printf("%d\n", ptr->top); // Ist 0 , OK
}
Here is a working stack implementation that store ints. This will afford you the opportunity to test that the operations work as expected. If you really want to store stack * replace the type. It seems unnecessarily confusing for a entry level class to have an assignment of storing pointers to the same thing you are building.
When you deal with pointers you want to make sure the object they point to outline the pointer. You may also want to think of shallow and deep copies with pointers. If you Pop followed by a Push the pointer that was returned from Pop now will point to the new value which would be surprising. Consider a different designs:
Pass in a reference to a variable (aka out parameter) so Pop(stack *s, *v) (and use an enum or define constants for error values).
return a value instead of a pointer; error would not be an out parameter.
return a pointer to a copy of the value and require client to free it.
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
typedef struct stack {
int elems[MAX];
int top;
} stack;
void Init(stack *s) {
if(!s)
return;
s->top = 0;
}
int IsEmpty(stack *s) {
return (s->top == 0);
}
void Push(stack *s, int elem) {
if (s->top == MAX) {
printf("Stack voll!");
return;
}
s->elems[s->top++] = elem;
}
int *Pop(stack *s) {
if (IsEmpty(s))
return NULL;
return &s->elems[--(s->top)];
}
int main() {
stack *s = malloc(sizeof *s);
Init(s);
printf("%d\n", s->top); // Ist 0 , OK
Push(s, 42);
int *v = Pop(s);
printf("%d\n", *v);
}
and example run:
0
42
Consider using a name prefix like "Stack" for all your symbols to avoid name conflicts.
In c we don't cast void * (from malloc()).

SIGSEV error in Circular queue function in c

Hey guys i have been trying to create circular queue library for my project purpose.But while developing a SIGEGV error from a if statement under empty function whenever i am using an condition at that particular if condition i am encountering this error.
#include <stdio.h>
#define SIZE 5
typedef struct queue
{
int values[SIZE];
int head;
int tail;
int size;
int count;
int full_flag;
}queue_t;
int init(queue_t* q)
{
//q->values;
q->head=-1;
q->tail=-1;
q->size=SIZE;
q->count=1;
q->full_flag=0;
}
int empty(queue_t* q) //This if statement where i am getting problem at
{
if(q->count==0)
{
return 1;
}
else
{
return 0;
}
}
int enqueue(queue_t* q,int input)
{
if(empty(q)==1)
{
printf("Queue is full\n");
}
else
{
if(q->head=-1)
{
q->head=0;
}
q->tail=(q->tail+1)%q->size;
q->values[q->tail]=input;
q->count++;
}
}
int deque(queue_t* q)
{
int result;
q->head=q->head%q->size;
result=q->values[q->head];
q->head++;
printf("Removing from %d\n",result);
q->count--;
}
int main(void) {
queue_t* q;
//q->head=5;
// q->values[2]=3;
init(q);
enqueue(q,2);
enqueue(q,3);
enqueue(q,4);
enqueue(q,5);
enqueue(q,6);
//printf("%d\n",q->values[q->tail]);
//printf("%d",q->head);
// your code goes here
return 0;
}
when i executing without that if loop everything works fine.BUt with it everything becoming a chaos.Please guys help me out thanks in advance
you have defined a pointer without allocating memory to it in your main function
queue_t* q;
this is a wild(dangling) pointer because it doesn't point to a specific piece of memory. you must allocate memory to it. like this:
queue_t* q = malloc(sizeof(queue_t));
or
queue_t q;
queue_t* pq = &q;

Am I freeing the dynamically allocated memories successfully?

I wrote a C program to practice DSA, specifically queues.
I wrote a function free_q() to free the dynamically allocated memories, but when I print the pointer to these structures, I get a memory address that is not equal to when I print %p NULL. I'd like to know why isn't the pointer Q set to NULL when freeing not only the dynam. all. structure but also the pointer to the array inside the structure.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct queue_rec
{
unsigned int front;
unsigned int rear;
unsigned int max_size;
unsigned int size;
int *arr_struct;
};
typedef struct queue_rec *QUEUE;
int
isEmpty(QUEUE Q)
{
return(Q->size==0);
}
int isFull(QUEUE Q)
{
return(Q->size>=Q->max_size);
}
QUEUE
create_queue(unsigned int size)
{
QUEUE Q = (QUEUE) malloc(sizeof(struct queue_rec));
if(Q==NULL){printf("Out of space!");}
else
{
Q->arr_struct = (int *) malloc(size * sizeof(int));
if(Q->arr_struct == NULL){printf("Out of space!");}
else
{
Q->size = 0;
Q->front = 1;
Q->rear = 0;
Q->max_size = size;
}
}
return Q;
}
unsigned int
succ(unsigned int value, QUEUE Q)
{
if(++value==Q->max_size){value=0;}
return value;
}
void
enqueue(int data, QUEUE Q)
{
if(isFull(Q)){printf("Queue is full!");}
else
{
Q->size++;
Q->rear = succ(Q->rear, Q);
Q->arr_struct[Q->rear] = data;
}
}
void
dequeue(QUEUE Q)
{
if(isEmpty(Q)){printf("Queue is empty!");}
else
{
Q->size--;
printf("%d", Q->arr_struct[Q->front]);
Q->front = succ(Q->front,Q);
}
}
void
free_q(QUEUE Q)
{
free(Q->arr_struct);
free(Q);
Q = NULL;
}
int main()
{
QUEUE Q = create_queue(4);
free_q(Q);
printf("%p\c", Q);
printf("%p", NULL);
return 0;
}
OUTPUT:
00031480
00000000
free takes a pointer as argument, which means that it can only alter what the pointer is pointing to. It cannot change the pointer point to another object.
void foo(int *p) {
// Code
}
int main(void) {
int x = 42;
int *p = &x;
int *q = &x;
foo(p);
if(p == q)
puts("Equal address"); // Guaranteed to be printed
if(*p == *q)
puts("Equal value"); // Depends on body of foo()
}
The above code is guaranteed to print "Equal address" irregardless of the body in foo. But it's NOT guaranteed to print "Equal value". If the signature instead was void foo(int **p) and you called it with foo(&p) it would have been different.
If you really want, you could do like this:
void
free_q(QUEUE *Q)
{
free((*Q)->arr_struct);
free(*Q);
*Q = NULL;
}
But I would in general not recommend such things. The need for nulling pointers can be a symptom that you don't have as much control as you think. When would you use it? To see if you have freed it properly? Not a good idea. Look at this:
QUEUE q = create_queue(42);
QUEUE p = q;
free_q(&q);
if(p == NULL) {
// OOOPS
Instead, I'd do like this:
typedef struct queue_rec QUEUE; // No pointer
QUEUE
create_queue(unsigned int size)
{
int *arr = malloc(size * sizeof *arr);
if(!arr){
fprintf(stderr, "Out of space");
exit(1);
}
return (QUEUE) { .max_size = size, .arr_struct = arr };
}
and if you for some reason want to dynamically allocate a whole queue, do it manually:
QUEUE *q = malloc(sizeof *q);
*q = create_queue(42);
Also, I would discourage typedefing pointers.

Prototype Declaration Error when Implementing a remove function for a Queue

I am trying to implement a queue in C, and I get a prototype declaration in my remove(q) method. I'm wondering what I'm doing wrong here, I am using an older version of queue implementation as an exercise, but cannot put this together.
#include <stdio.h>
#define MAXQUEUE 100
#define TRUE (1==1)
#define FALSE (1==0)
struct queue {
int items[MAXQUEUE];
int front, rear;
};
empty(pq)
struct queue *pq;
{
return ((pq->front == pq->rear) ? TRUE : FALSE);
}
remove(pq)
struct queue *pq;
{
if (empty(pq)) {
printf("queue underflow\n");
exit(1);
}
if (pq->front == MAXQUEUE - 1)
pq->front = 0;
else
(pq->front)++;
return (pq->items[pq->front]);
}
int main() {
struct queue q;
q.front = q.rear = MAXQUEUE - 1;
if (empty(q)) {
printf("hello");
} else
printf("\n sod off\n");
return 0;
}
Your functions aren't functions. You need to adjust them to take a queue as an arguments and return your values like so:
int empty(struct queue *pq)
{
return ((pq->front == pq ->rear) ? TRUE : FALSE);
}
int remove(struct queue *pq)
{
if(empty(pq)){
printf("queue underflow\n");
exit(1);
}
if(pq->front == MAXQUEUE-1)
pq->front = 0;
else
(pq->front)++;
return (pq->items[pq->front]);
}
Making these changes along with one change in your main (if (empty(q) -> if (empty(&q)) compiles and outputs hello.
what if you declare your functions like this:
void
empty(struct queue *pq)
{
...
}
and
void
remove(struct queue *pq)
{
...
}

Is it possible to have a linked list of different data types?

This is just another interview question.
Can we have a linked list of different data types, i.e. each element in a linked list can have different structure or union elements? If it's possible can you please explain with an example?
Well in a linked list you don't HAVE to link like for like structs together. As long as they have the appropriate forward and/or backwards pointers you are fine. For example:
struct BaseLink
{
BaseLink* pNext;
BaseLink* pPrev;
int typeId;
};
struct StringLink
{
BaseLink baseLink;
char* pString;
};
struct IntLink
{
BaseLink baseLink;
int nInt;
};
This way you'd have a linked list that goes from BaseLink to BaseLink. The extra data is not a problem. You want to see it as a StringLink? Then cast the BaseLink to a StringLink.
Just remember that you need some form of typeid in there so you know what to cast it to when you arrive at it.
Use union to create the datatype
union u_tag{
char ch;
int d;
double dl;
};
struct node {
char type;
union u_tag u;
struct node *next;
};
Use struct node to create linked list. type decides what is the datatype of the data.
Harsha T, Bangalore
You can use a union type:
enum type_tag {INT_TYPE, DOUBLE_TYPE, STRING_TYPE, R1_TYPE, R2_TYPE, ...};
struct node {
union {
int ival;
double dval;
char *sval;
struct recordType1 r1val;
struct recordType2 r2val;
...
} data;
enum type_tag dataType;
struct node *prev;
struct node *next;
};
Another method I've explored is to use a void* for the data and attach pointers to functions that handle the type-aware stuff:
/**
* Define a key type for indexing and searching
*/
typedef ... key_t;
/**
* Define the list node type
*/
struct node {
void *data;
struct node *prev;
struct node *next;
void *(*cpy)(void *); // make a deep copy of the data
void (*del)(void *); // delete the data
char *(*dpy)(void *); // format the data for display as a string
int (*match)(void *, key_t); // match against a key value
};
/**
* Define functions for handling a specific data type
*/
void *copyARecordType(void *data)
{
struct aRecordType v = *(struct aRecordType *) data;
struct aRecordType *new = malloc(sizeof *new);
if (new)
{
// copy elements of v to new
}
return new;
}
void deleteARecordType(void *data) {...}
char *displayARecordType(void *data) {...}
int matchARecordType(void *data, key_t key) {...}
/**
* Define functions for handling a different type
*/
void *copyADifferentRecordType(void *data) {...}
void deleteADifferentRecordType(void *data) {...}
char *displayADifferentRecordType(void *data) {...}
int matchADifferentRecordType(void *data, key_t key) {...}
/**
* Function for creating new list nodes
*/
struct node *createNode(void *data, void *(*cpy)(void *), void (*del)(void *),
char *(*dpy)(void *), int (*match)(void *, key_t))
{
struct node *new = malloc(sizeof *new);
if (new)
{
new->cpy = cpy;
new->del = del;
new->dpy = dpy;
new->match = match;
new->data = new->cpy(data);
new->prev = new->next = NULL;
}
return new;
}
/**
* Function for deleting list nodes
*/
void deleteNode(struct node *p)
{
if (p)
p->del(p->data);
free(p);
}
/**
* Add new node to the list; for this example, we just add to the end
* as in a FIFO queue.
*/
void addNode(struct node *head, void *data, void *(*cpy)(void*),
void (*del)(void *), char *(*dpy)(void *), int (*match)(void*, key_t))
{
struct node *new = createNode(data, cpy, del, dpy, match);
if (!head->next)
head->next = new;
else
{
struct node *cur = head->next;
while (cur->next != NULL)
cur = cur->next;
cur->next = new;
new->prev = cur;
}
}
/**
* Examples of how all of this would be used.
*/
int main(void)
{
struct aRecordType r1 = {...};
struct aDifferentRecordType r2 = {...};
struct node list, *p;
addNode(&list, &r1, copyARecordType, deleteARecordType, displayARecordType,
matchARecordType);
addNode(&list, &r2, copyADifferentRecordType, deleteADifferentRecordType,
displayADifferentRecordType, matchADifferentRecordType);
p = list.next;
while (p)
{
printf("Data at node %p: %s\n", (void*) p, p->dpy(p->data));
p = p->next;
}
return 0;
}
Obviously, I've left out some error checking and handling code from this example, and I don't doubt there are a host of problems with it, but it should be illustrative.
You can have each node in a linked list have a void* that points to your data. It's up to you how you determine what type of data that pointer is pointing to.
If you don't want to have to specify the type of every node in the list via the union solution you can always just store the data in a char* and take type-specific function pointers as parameters to type-sensitive operations such as printing or sorting the list.
This way you don't have to worry about what node is what type and can just cast the data however you like.
/* data types */
typedef struct list_node list_node;
struct list_node {
char *data;
list_node *next;
list_node *prev;
};
typedef struct list list;
struct list {
list_node *head;
list_node *tail;
size_t size;
};
/* type sensitive functions */
int list_sort(list *l, int (*compar)(const void*, const void*));
int list_print(list *l, void (*print)(char *data));
Yes, I do this by defining the list's element's value as a void pointer void*.
In order to know the type stored in each element of the list I also have a .type field in there, so I know how to dereference what the pointer is pointing to for each element.
struct node {
struct node* next;
int type;
void* value;
};
Here's a full example of this:
//
// An exercise to play with a struct that stores anything using a void* field.
//
#include <stdio.h>
#define TRUE 1
int TYPE_INT = 0;
int TYPE_STRING = 1;
int TYPE_BOOLEAN = 2;
int TYPE_PERSON = 3;
struct node {
struct node* next;
int type;
void* value;
};
struct person {
char* name;
int age;
};
int main(int args, char **argv) {
struct person aPerson;
aPerson.name = "Angel";
aPerson.age = 35;
// Define a linked list of objects.
// We use that .type field to know what we're dealing
// with on every iteration. On .value we store our values.
struct node nodes[] = {
{ .next = &nodes[1], .type = TYPE_INT , .value=1 },
{ .next = &nodes[2], .type = TYPE_STRING , .value="anyfing, anyfing!" },
{ .next = &nodes[3], .type = TYPE_PERSON , .value=&aPerson },
{ .next = NULL , .type = TYPE_BOOLEAN, .value=TRUE }
};
// We iterate through the list
for ( struct node *currentNode = &nodes[0]; currentNode; currentNode = currentNode->next) {
int currentType = (*currentNode).type;
if (currentType == TYPE_INT) {
printf("%s: %d\n", "- INTEGER", (*currentNode).value); // just playing with syntax, same as currentNode->value
} else if (currentType == TYPE_STRING) {
printf("%s: %s\n", "- STRING", currentNode->value);
} else if (currentType == TYPE_BOOLEAN) {
printf("%s: %d\n", "- BOOLEAN (true:1, false:0)", currentNode->value);
} else if (currentType == TYPE_PERSON) {
// since we're using void*, we end up with a pointer to struct person, which we *dereference
// into a struct in the stack.
struct person currentPerson = *(struct person*) currentNode->value;
printf("%s: %s (%d)\n","- TYPE_PERSON", currentPerson.name, currentPerson.age);
}
}
return 0;
}
Expected output:
- INTEGER: 1
- STRING: anyfing, anyfing!
- TYPE_PERSON: Angel (35)
- BOOLEAN (true:1, false:0): 1
As said, you can have a node this questionwith a void*. I suggest using something to know about your type :
typedef struct
{
/* linked list stuff here */
char m_type;
void* m_data;
}
Node;
See this question.
Actually, you don't have to put the pointer first in the structure, you can put it anywhere and then find the beginning fo the struct with a containerof() macro. The linux kernel does this with its linked lists.
http://isis.poly.edu/kulesh/stuff/src/klist/
I use these macros I wrote to make general linked lists. You just create your own struct and use the macro list_link somewhere as a member of the struct. Give that macro one argument naming the struct (without the struct keyword). This implements a doubly linked list without a dummy node (e.g. last node links back around to first node). The anchor is a pointer to the first node which starts out initialized by list_init(anchor) by giving it the lvalue (a dereferenced pointer to it is an lvalue). Then you can use the other macros in the header. Read the source for comments about each available macro functions. This is implemented 100% in macros.
http://phil.ipal.org/pre-release/list-0.0.5.tar.bz2
Yes,Sure You can insert any data type values in the linked list I've designed and its very simple to do so.I have used different constructors of node and boolean variables to check that which type value is inserted and then I do operation and command according to that value in my program.
//IMPLEMENTATION OF SINGLY LINKED LISTS
#include"iostream"
#include"conio.h"
#include <typeinfo>
using namespace std;
class node //struct
{
public:
node* nextptr;
int data;
////////////////////////////////just to asure that user can insert any data type value in the linked list
string ss;
char cc;
double dd;
bool stringTrue=0;
bool intTrue = 0;
bool charTrue = 0;
bool doubleTrue = 0;
////////////////////////////////just to asure that user can insert any data type value in the linked list
node()
{
nextptr = NULL;
}
node(int d)
{
data = d;
nextptr = NULL;
intTrue = 1;
}
////////////////////////////////just to asure that user can insert any data type value in the linked list
node(string s)
{
stringTrue = 1;
ss = s;
nextptr = NULL;
}
node(char c)
{
charTrue = 1;
cc = c;
nextptr = NULL;
}
node(double d)
{
doubleTrue = 1;
dd = d;
nextptr = NULL;
}
////////////////////////////////just to asure that user can insert any data type value in the linked list
//TO Get the data
int getintData()
{
return data;
}
string getstringData()
{
return ss;
}
double getdoubleData()
{
return dd;
}
char getcharData()
{
return cc;
}
//TO Set the data
void setintData(int d)
{
data = d;
}
void setstringData(string s)
{
ss = s;
}
void setdoubleData(double d)
{
dd = d;
}
void setcharData(char c)
{
cc = c;
}
char checkWhichInput()
{
if (intTrue == 1)
{
return 'i';
}
else if (stringTrue == 1)
{
return 's';
}
else if (doubleTrue == 1)
{
return 'd';
}
else if (charTrue == 1)
{
return 'c';
}
}
//////////////////////////////Just for the sake of implementing for any data type//////////////////////////////
node* getNextptr()
{
return nextptr;
}
void setnextptr(node* nptr)
{
nextptr = nptr;
}
};
class linkedlist
{
node* headptr;
node* addnodeatspecificpoition;
public:
linkedlist()
{
headptr = NULL;
}
void insertionAtTail(node* n)
{
if (headptr == NULL)
{
headptr = n;
}
else
{
node* rptr = headptr;
while (rptr->getNextptr() != NULL)
{
rptr = rptr->getNextptr();
}
rptr->setnextptr(n);
}
}
void insertionAtHead(node *n)
{
node* tmp = n;
tmp->setnextptr(headptr);
headptr = tmp;
}
int sizeOfLinkedList()
{
int i = 1;
node* ptr = headptr;
while (ptr->getNextptr() != NULL)
{
++i;
ptr = ptr->getNextptr();
}
return i;
}
bool isListEmpty() {
if (sizeOfLinkedList() <= 1)
{
return true;
}
else
{
false;
}
}
void insertionAtAnyPoint(node* n, int position)
{
if (position > sizeOfLinkedList() || position < 1) {
cout << "\n\nInvalid insertion at index :" << position;
cout <<".There is no index " << position << " in the linked list.ERROR.\n\n";
return;
}
addnodeatspecificpoition = new node;
addnodeatspecificpoition = n;
addnodeatspecificpoition->setnextptr(NULL);
if (headptr == NULL)
{
headptr = addnodeatspecificpoition;
}
else if (position == 0)
{
addnodeatspecificpoition->setnextptr(headptr);
headptr = addnodeatspecificpoition;
}
else
{
node* current = headptr;
int i = 1;
for (i = 1; current != NULL; i++)
{
if (i == position)
{
addnodeatspecificpoition->setnextptr(current->getNextptr());
current->setnextptr(addnodeatspecificpoition);
break;
}
current = current->getNextptr();
}
}
}
friend ostream& operator<<(ostream& output,const linkedlist& L)
{
char checkWhatInput;
int i = 1;
node* ptr = L.headptr;
while (ptr->getNextptr() != NULL)
{
++i;
checkWhatInput = ptr->checkWhichInput();
/// <summary>
switch (checkWhatInput)
{
case 'i':output <<ptr->getintData()<<endl;
break;
case 's':output << ptr->getstringData()<<endl;
break;
case 'd':output << ptr->getdoubleData() << endl;
break;
case 'c':output << ptr->getcharData() << endl;
break;
default:
break;
}
/// </summary>
/// <param name="output"></param>
/// <param name="L"></param>
/// <returns></returns>
ptr = ptr->getNextptr();
}
/// <summary>
switch (checkWhatInput)
{
case 'i':output << ptr->getintData() << endl;
break;
case 's':output << ptr->getstringData() << endl;
break;
case 'd':output << ptr->getdoubleData() << endl;
break;
case 'c':output << ptr->getcharData() << endl;
break;
default:
break;
}
/// </summary>
/// <param name="output"></param>
/// <param name="L"></param>
/// <returns></returns>
if (ptr->getNextptr() == NULL)
{
output << "\nNULL (There is no pointer left)\n";
}
return output;
}
~linkedlist() {
delete addnodeatspecificpoition;
}
};
int main()
{
linkedlist L1;
//Insertion at tail
L1.insertionAtTail(new node("dsaf"));
L1.insertionAtTail(new node("sadf"));
L1.insertionAtTail(new node("sfa"));
L1.insertionAtTail(new node(12));
L1.insertionAtTail(new node(67));
L1.insertionAtTail(new node(23));
L1.insertionAtTail(new node(45.677));
L1.insertionAtTail(new node(12.43556));
//Inserting a node at head
L1.insertionAtHead(new node(1));
//Inserting a node at any given point
L1.insertionAtAnyPoint(new node(999), 3);
cout << L1;
cout << "\nThe size of linked list after insertion of elements is : " << L1.sizeOfLinkedList();
}
The output is
1
dsaf
sadf
999
sfa
12
67
23
45.677
12.4356
Thats what you can use to create a linked list without worrying of data type
Just an FYI, In C# you can use Object as your data member.
class Node
{
Node next;
Object Data;
}
User can then use something like this to find out which Object the Node stores:
if (obj.GetType() == this.GetType()) //
{
}

Resources