Created
April 18, 2013 18:01
-
-
Save jacobabrahamb4/5414867 to your computer and use it in GitHub Desktop.
single linked list, only functions are included, will be implemented later.....
This file contains hidden or 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
//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.... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment