Skip to content

Instantly share code, notes, and snippets.

@sXakil
Last active April 14, 2019 10:38
Show Gist options
  • Select an option

  • Save sXakil/76edc55a620917ad78b2c28fb37fa688 to your computer and use it in GitHub Desktop.

Select an option

Save sXakil/76edc55a620917ad78b2c28fb37fa688 to your computer and use it in GitHub Desktop.
Reverse a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
typedef struct Node *NodePtr;
NodePtr head = NULL;
void newNode(int); //creates a new independent node
void seeder(); //fills the array with some values
void printList(); //prints out all the elements in the list
void reverse(); //does the reversing
int main() {
seeder();
printf("Original List: ");
printList();
reverse();
printf("Reversed List: ");
printList();
}
void newNode(int data) {
NodePtr newNode = (NodePtr) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL)
head = newNode;
else {
NodePtr trav = head;
while (trav->next != NULL) {
trav = trav->next;
}
trav->next = newNode;
}
}
void seeder() {
int i;
for (i = 20; i <= 50; i += 2)
newNode(i);
}
void printList() {
NodePtr trav = head;
printf("\n[");
while (trav != NULL) {
printf("%d", trav->data);
trav = trav->next;
if (trav != NULL)
printf(", ");
}
printf("]\n");
}
void reverse() {
NodePtr curr = head;
NodePtr prev = NULL;
NodePtr temp = NULL;
while (curr != NULL) {
temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
head = prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment