Skip to content

Instantly share code, notes, and snippets.

@jitsceait
Last active November 27, 2015 03:56
Show Gist options
  • Save jitsceait/0fb96f481c3f5747044b to your computer and use it in GitHub Desktop.
Save jitsceait/0fb96f481c3f5747044b to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node * next;
} Node;
Node * create_node(int val){
Node * temp = (Node *)malloc(sizeof(Node));
if(temp){
temp->data = val;
temp->next = NULL;
}
return temp;
}
/* This function inserts node at the head of linked list */
void push(Node **headRef, int data){
Node * new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = *headRef;
*headRef = new_node;
}
void print_list(Node * head){
while(head){
printf("%d->", head->data);
head = head->next;
}
printf("Null");
}
Node * reverse_linked_list(Node * head){
/* We are not passing reference to head, as we will be returning changed
head pointer */
if(!head) return NULL;
Node * current = head;
Node * previous = NULL;
Node * next = NULL;
while(current){
next = current ->next;
current->next = previous;
previous = current;
current = next;
}
return previous;
}
int main(void) {
Node * head = NULL;
push(&head, 3);
push(&head, 4);
push(&head, 5);
push(&head, 6);
push(&head, 7);
printf("\n Original list :");
print_list(head);
head = reverse_linked_list(head);
printf("\n Reverse list :");
print_list(head);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment