Linked List ในภาษา C 

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

typedef struct Nodex
{
int data;
Nodex* next;
} Node ;
typedef struct List
{
int size;
Node * head;
} LinkedList;

void addFirst(LinkedList* ll , int data )
{
if(ll->head == NULL)
{
ll->head = (Node*)malloc(sizeof(Node));
ll->head->data = data;
ll->head->next = NULL;
}
else
{
Node * n= (Node*)malloc(sizeof(Node));
n->data = data;
n->next = ll->head;
ll->head = n;
}
ll->size ++;
}

void addLast(LinkedList* ll , int data )
{
if(ll->head == NULL)
{
ll->head = (Node*)malloc(sizeof(Node));
ll->head->data = data;
ll->head->next = NULL;
}
else
{
Node * n= (Node*)malloc(sizeof(Node));
n->data = data;
n->next = NULL;
Node * k = ll->head;

while(k->next != NULL)
{
k=k->next;
}

k->next = n;
}
ll->size ++;
}

void insert(LinkedList* ll , int data,int at)
{
if(ll->head == NULL)
{
if(at ==0 )
{
ll->head = (Node*)malloc(sizeof(Node));
ll->head->data = data;
ll->head->next = NULL;
}
}
else
{
Node * k = ll->head;
int i=0;
while(k->next != NULL&& i < at-1)
{
k=k->next;
i++;
}
Node * n= (Node*)malloc(sizeof(Node));
n->data = data;
n->next = k->next ;
k->next = n;
}
ll->size ++;
}

void print(LinkedList* ll)
{
Node * k = ll->head;
int i=0;
while(k != NULL)
{
printf(" [%d]-> ",k->data, k->next );
k=k->next;
i++;
}
printf("\n");
}
void removeLast(LinkedList * ll)
{
if(ll->head == NULL) return;
if(ll->size == 1)
{
free (ll->head);
ll->head = NULL;
ll->size --;
return;
}
Node * k = ll->head;
int i=0;
while(k->next->next != NULL )
{
k=k->next;
i++;
}
free (k->next);
k->next = NULL;
ll->size --;

}


void sort(LinkedList * ll)
{
if(ll->head == NULL) return ;
int s = ll->size;
int i = 0 ;
int m;
for(;i < s ; i++)
{
Node * k = ll->head;
int j=0;
while(k->next != NULL && j < s- i )
{
if( k->data > k->next->data)
{
m = k->data;
k->data = k->next->data;
k->next->data = m;
}
k=k->next;
j++;
}
}
}
void removeFirst(LinkedList * ll)
{
if(ll->head == NULL) return;

Node * n= ll->head;
ll->head = ll->head->next;
free(n);

ll->size --;
}

void deleteListAll(LinkedList * ll)
{
while(ll->size > 0 )
{
removeFirst( ll);
}
}

int main(int argc,char* argv[])
{

LinkedList ll;
ll.head = NULL;
ll.size = 0;
addFirst (&ll,5);
addFirst (&ll,15);
addFirst (&ll,3);
addFirst (&ll,4);
addFirst (&ll,2);
addLast (&ll,21);
insert (&ll,40,1);

print (&ll);
sort(&ll);
print (&ll);


deleteListAll(&ll);

return 0;
}





[ view entry ] ( 1744 views )   |  permalink  |  $star_image$star_image$star_image$star_image$star_image ( 3 / 1129 )

<<First <Back | 1 | 2 | 3 | 4 | 5 | Next> Last>>