Skip to content

Instantly share code, notes, and snippets.

@Charles-Hsu
Last active November 26, 2019 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Charles-Hsu/28fa2362672ea21a4b4d7e2e1df643bd to your computer and use it in GitHub Desktop.
Save Charles-Hsu/28fa2362672ea21a4b4d7e2e1df643bd to your computer and use it in GitHub Desktop.
Linked List
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
int data;
struct node *next;
};
struct node *head = NULL;
void insert_first (int key, int data)
{
/* allocate memory for this node */
struct node *link = (struct node *) malloc (sizeof(struct node));
link->key = key;
link->data = data;
/* point it to old first node */
link->next = head;
/* point first to new first node */
head = link;
}
void print_list()
{
struct node *current = head;
while (current != NULL) {
printf ("[%d,%d]\n", current->key, current->data);
current = current->next;
}
}
void delete_first()
{
struct node *tmp = head->next;
free (head);
head = tmp;
}
void reverse()
{
struct node *new_head = NULL;
struct node *current = head;
struct node *temp;
while (current != NULL) {
struct node *link = (struct node *) malloc (sizeof(struct node));
link->key = current->key;
link->data = current->data;
link->next = current->next;
new_head = link;
temp = current;
current = current->next;
free (temp);
}
head = new_head;
}
int main(void)
{
printf ("is empty linked list? %s\n", is_empty() ? "YES" : "NO");
insert_first (1, 38);
insert_first (2, -15);
insert_first (3, 87);
print_list();
while (!is_empty()) {
struct node *temp = delete_first();
printf ("Deleted value:");
printf ("[%d, %d]\n", temp->key, temp->data);
free (temp);
}
insert_first (1, 38);
insert_first (2, -15);
insert_first (3, 87);
print_list();
printf ("reverse linked list:\n");
reverse();
print_list();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment