I want to reverse a linked list and my code doesn't seem to work. I don't know what is wrong with it. I used a reverse()
function I found here, I even tested it on paper so I'm pretty sure the code is good but I must be missing something still. I'd love to find out what is wrong. Here is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node * next;
}node;
void push(int val, node **head){
node* temp=(node*)malloc(sizeof(node));
node* current=*head;
temp->val=val;
if(*head==NULL)
{*head=temp;
temp->next=NULL;}
else
{while(current->next!=NULL)
current=current->next;
current->next=temp;
temp->next=NULL;}
}
int reverse(node * head){
node *previous = NULL;
node *current = head;
node *forward;
while (current != NULL) {
forward = current->next;
current->next = previous;
previous = current;
current = forward;
}
return previous;
}
void print(node *new_head){
node* current2=new_head;
current2=current2->next;
while(current2!=NULL)
{
printf("%d", current2->val);
current2=current2->next;
}}
int main()
{ node * head= NULL;
int n;
node * new_head;
scanf("%d", &n);
push(n,head);
scanf("%d", &n);
push(n,head);
scanf("%d", &n);
push(n,head);
new_head=reverse(head);
print(new_head);
return 0;}
I just want to reverse an input like: 1,2,3. So the output would be 3,2,1.