I have created a linked list but couldn't think of how to reverse the same. I know the algo but i think i have made a mistake in creating the list. What could be the change in reverse function so that it work. Following is the code:
typedef struct Node{
int data;
struct Node* next;
} node;
node* head;
int count;
void insertAtBegin(int value){
if(head==NULL){
head = (node*)malloc(sizeof(node));
head->data = 0;
head->next = NULL;
}
node* newNode = (node*)malloc(sizeof(node));
newNode->data = value;
newNode->next = head->next;
head->next = newNode;
count++;
}
void display(){
node* temp = (node*)malloc(sizeof(node));
temp = head;
while(temp->next!=NULL){
printf("%d\t",temp->next->data);
temp = temp->next;
}
printf("\n");
}
void reverse(){
node *p, *q, *r;
p = q = r = head;
p = p->next->next;
q = q->next;
r->next = NULL;
q->next = r;
while (p != NULL){
r = q;
q = p;
p = p->next;
q->next = r;
}
head = q;
}
void main(){
insertAtBegin(5);
insertAtBegin(6);
display();
reverse();
display();
printf("\nSize of linked list is %d",count);
}