Skip to content

Instantly share code, notes, and snippets.

@hiepph
Created September 28, 2015 11:48
Show Gist options
  • Save hiepph/8114f44357e6498e61f2 to your computer and use it in GitHub Desktop.
Save hiepph/8114f44357e6498e61f2 to your computer and use it in GitHub Desktop.
[Header File] Single Linked List Implementation
/** Singly Linked List (include Sort Ascending)
insert, remove, add, count source code
**/
#ifndef SLL_H
#define SLL_H
typedef ... data_t;
struct node
{
data_t data;
struct node *next;
} *root; // global varibale pointer ROOT
/* Treo them 1 node o cuoi danh sach */
void append(data_t NewData)
{
struct node *tem, *right;
tem = (struct node *)malloc(sizeof(struct node));
tem->data = NewData;
right = (struct node*)root; // chay tu dau
while(right->next!=NULL)
right = right->next; // chay den node cuoi cung
right->next = tem;
right = tem;
right->next = NULL;
}
/* Them 1 node vao dau danh sach */
void add(data_t NewData)
{
struct node *tem;
tem = (struct node*)malloc(sizeof(struct node));
tem->data = NewData;
if(root==NULL) // list chua co 1 phan tu nao
{
root = tem;
root->next = NULL;
}
else
{
tem->next = root;
root = tem;
}
}
/* Chen vao giua */
void addAfter(data_t NewData, int loc) // loc: location i want to add to
{
int i;
struct node *tem, *left, *right;
right = root;
for(i=1; i<loc; i++)
{
left = right;
right = right->next;
}
tem = (struct node *)malloc(sizeof(struct node));
tem->data = NewData;
left->next = tem;
left = tem;
left->next = right;
}
void insert(data_t NewData)
{
struct node *tem;
tem = root;
if(tem==NULL)
{
add(NewData);
}
else
{
int c=0;
while(tem!=NULL)
{
if(tem->data<NewData)
c++;
tem = tem->next;
}
if(c==0) // min (add dau)
add(NewData);
else if(c<count())
addAfter(NewData,++c); // gia tri tam trung trung
else
append(NewData); // max (append cuoi)
}
}
/* Dem so phan tu node */
int count()
{
struct node *n;
int c=0;
n = root;
while(n!=NULL)
{
n = n->next;
c++;
}
return c;
}
void display(struct node *r)
{
r = root;
if(r==NULL)
{
return;
}
while(r!=NULL)
{
printf("%d ",r->data);
r = r->next;
}
printf("\n");
}
int delete(data_t DeleteData)
{
struct node *tem, *prev;
tem = root;
while(tem!=NULL)
{
if(tem->data==DeleteData)
{
if(tem==root) // be careful with root (must be survived)
{
root = tem->next;
free(tem);
return 1;
}
else
{
prev->next = tem->next;
free(tem);
return 1;
}
}
else
{
prev = tem;
tem = tem->next;
}
}
return 0;
}
/* Reverse list */
struct node* reverse()
{
struct node *cur, *prev;
cur = prev = NULL;
while(root != NULL) {
cur = root;
root = root->next;
cur->next = prev;
prev = cur;
}
return prev;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment