Skip to content

Instantly share code, notes, and snippets.

@jacobabrahamb4
Created April 18, 2013 18:01

Revisions

  1. jacobabrahamb4 created this gist Apr 18, 2013.
    100 changes: 100 additions & 0 deletions single_linked_list.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,100 @@
    //http://www.zentut.com/c-tutorial/c-linked-list/


    #include <stdio.h>
    #include <stdlib.h>

    typedef struct node{
    int data;
    node* next=NULL;
    } node;

    node* head = NULL

    typedef void (*callback)(node*);


    // create a new node and allocate memory
    node* create_node(int data, node* next)
    {
    node* new_node = (node*)malloc(sizeof(node));
    if(new_node==NULL)
    {
    printf("Error creating a new node. \n");
    exit(1);
    }
    new_node->data = data;
    new_node->next = next;
    return new_node;
    }
    // add a node at the beginning of the list

    node* prepend(node* head, int data)
    {
    node* new_node = create_node(data, head);
    head = new_node;
    return head;
    }
    // add a new node at the end of the list
    node* append(node* head, int data)
    {
    if(head==NULL) return NULL;
    node* cursor = head;
    while(cursor->next!=NULL) cursor = cursor->next;
    cursor->next = create_node(data, NULL)
    return head;
    }
    // insert a new node after the previous node

    node* insert_after(node* head, int data, node* previous)
    {
    if(head==NULL || previous == NULL) return NULL;
    previous->next = create_node(data, previous->next);
    }

    // insert a new node before a next node

    node* insert_before(node* head, int data, node* next)
    {
    if(head == NULL || next==NULL) return NULL;
    node* cursor = head;
    while(cursor->next != next) cursor = cursor->next;
    cursor->next = create_node(data, next);
    return head;
    }

    // remove a node from the list

    node* remove_node(node* nde)
    {
    if(nde == NULL || head == NULL) return NULL;
    node* cursor = head;
    while(cursor->next!=nde) cursor = cursor->next;
    cursor->next=nde->next;
    free(nde);
    }

    // reverse the linked list

    node* reverse(node* head)
    {
    node* cursor = head;
    while(true)
    {
    node* next = cursor->next->next;
    cursor->next->next = cursor;
    cursor = cursor->next;
    if(next==NULL) break;
    }
    head->next=NULL;
    return (head=cursor);
    }





    int main()
    {
    // implement methods to use those functions here....
    }