Skip to content

Instantly share code, notes, and snippets.

@shiblisec
Created October 31, 2018 12:10
Show Gist options
  • Save shiblisec/c9e482ca3fe66dda3e48f4749f500bc9 to your computer and use it in GitHub Desktop.
Save shiblisec/c9e482ca3fe66dda3e48f4749f500bc9 to your computer and use it in GitHub Desktop.
C program to reverse a Linked List
#include<stdio.h>
#include<stdlib.h>
struct node{
int value;
struct node *next;
};
struct node *HEAD = NULL;
struct node *temp, *y;
void insert(value){
if(HEAD == NULL){
temp = (struct node *)malloc(sizeof(struct node));
HEAD = temp;
temp->value = value;
temp->next = NULL;
}
else{
y = temp;
temp = (struct node *)malloc(sizeof(struct node));
y->next = temp;
temp->value = value;
temp->next = NULL;
}
}
void display(){
struct node *j;
j = HEAD;
while(j != NULL){
printf("%d ",j->value);
j = j->next;
}
printf("\n");
}
void reverse(){
struct node *j, *next, *prev;
j = HEAD;
while(j != NULL){
next = j->next;
if(j==HEAD){
j->next = NULL;
prev = j;
}
else{
j->next = prev;
prev = j;
}
j = next;
}
HEAD = prev;
}
int main(){
insert(20);
insert(30);
insert(40);
insert(23);
display();
reverse();
display();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment