-
-
Save shiblisec/c9e482ca3fe66dda3e48f4749f500bc9 to your computer and use it in GitHub Desktop.
C program to reverse a Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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