Reputation: 323
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
void init(node* head, node* tail){
head = (node*)malloc(sizeof(node));
tail = (node*)malloc(sizeof(node));
head->next = tail;
tail->next = tail;
}
void push(node* head, int data){
node *temp;
temp = (node*)malloc(sizeof(node));
if(temp == NULL){
printf("%s", "Out Of Memory");
}else{
temp->data = data;
temp->next = head->next;
on the next Line, there there's printf method which print number 7. It's for debug. but this printf methods didn't worked. so I noticed
temp->next = head->next;
this code has an error. but I couldn't find the reason.. I was thinking of memory allocation issue. but still didn't get it..!
printf("%d", 7);
head->next = temp;
printf("push (%d)", data);
}
}
void main(){
node* head = NULL;
node* tail = NULL;
init(head, tail);
push(head, 10);
}
Upvotes: 0
Views: 80
Reputation: 44368
1) You don't need nor want an initialization function. The stack is considered empty when head
is NULL. So head = NULL;
is sufficient initialization.
2) A stack don't need a tail
pointer as elements are always inserted/removed at the front
3) Your push
function must allow for update of head
One way is to return the new head. Another is to pass a pointer to head
4) A linked list doesn't have tail->next = tail;
The end of the list is reached when next
is NULL. So if you have a tail
it would be tail->next = NULL;
A stack using "return of new head" is more like:
node* push(node* head, int data){
node *temp = malloc(sizeof(node));
if(temp == NULL){
printf("%s", "Out Of Memory");
return head;
}
temp->data = data;
temp->next = head; // notice this
return temp;
}
int main(){
node* head = NULL;
head = push(head, 10);
return 0;
}
And a stack using "pass pointer to head" is more like:
void push(node** headPtr, int data){
node *temp = malloc(sizeof(node));
if(temp == NULL){
printf("%s", "Out Of Memory");
return;
}
temp->data = data;
temp->next = *headPtr; // notice the *
*headPtr = temp;
}
int main(){
node* head = NULL;
push(&head, 10); // notice the &
return 0;
}
Upvotes: 1
Reputation: 1078
void init(node** head, node** tail){
*head = malloc(sizeof(node));
*tail = malloc(sizeof(node));
(*head)->next = *tail;
(*tail)->next = *tail;
}
void main(){
node* head = NULL;
node* tail = NULL;
init(&head, &tail);
push(head, 10);
}
You should pass head and tail as pass by reference to reflect the changed values of head and tail in calling function main().
For more information on pass by reference check this
Upvotes: 3
Reputation: 11
You can remove the init function all together from your code and the tail is not necessary. If you want to use it for debugging, your main can look like this.
node* head = NULL;
node* tail = NULL;
head = (node*)malloc(sizeof(node));
tail = (node*)malloc(sizeof(node));
head->next = tail;
tail->next = tail;
Upvotes: 1