您的位置:首页 > 其它

单链表基本操作c语实现

2008-03-29 10:33 411 查看
整理了下以前的代码,放到这里来,防止又被我格了(上次很多被不小心格了,哭啊!) 。

单链表的一些操作:


//:linkList.c




#include <stdio.h>


#include <malloc.h>


#include <conio.h>




//define a node




typedef struct node...{


int val;


struct node *next;


} node;




//create a link list by tail inserting




void tail_insert(node **h,int i)...{




if (*h == 0)...{


*h = (node*)malloc(sizeof(node));


(*h)->val = i;


(*h)->next = 0;


return;


}


node *p = (node*)malloc(sizeof(node)),*pl = *h;


p->val = i;


p->next = 0;


while (pl->next)


pl = pl->next;


pl->next = p;


return;


}




//create a link list by head inserting




void head_insert(node **h,int i)...{




if (*h == 0)...{


*h = (node*)malloc(sizeof(node));


(*h)->next = 0;


(*h)->val = i;


return;


}


node *p = (node*)malloc(sizeof(node));


p->val = i;


p->next = *h;


*h = p;


return;


}




//reverse a link list by iteration




node* reverse_iteration(node *h)...{


node *nh = h,*p = 0;


h = h->next;


nh->next = 0;




while (h)...{


p = h;


h = h->next;


p->next = nh;


nh = p;


}


return nh;


}




//reverse a link list by recursion




node * reverse_recursion(node *h)...{


if (!h || !h->next)


return h;


node *p = h->next,*r = 0;


r = reverse_recursion(p);


p->next = h;


h->next = 0;


return r;


}




//order link list by using typical algorithm


//insertion sort




node* insertionSortL(node *h)...{


node *sorted = h,*unsorted = sorted->next,


*p1 = 0,*p2 = 0;




while (unsorted)...{




if (unsorted->val < h->val)...{


sorted->next = unsorted->next;


unsorted->next = h;


h = unsorted;


}




else...{


p1 = h;


p2 = p1->next;




while (unsorted->val > p2->val)...{


p1 = p2;


p2 = p2->next;


}




if (p2 != unsorted)...{


sorted->next = unsorted->next;


p1->next = unsorted;


unsorted->next = p2;


}


else


sorted = unsorted;


}


unsorted = sorted->next;


}


return h;


}




//quick sort




node* quickSortL(node *h,node *t)...{


if (h == t)


return h;


node *pl = h,*pr = t,*p1 = h->next,*p2 = 0;




while (p1 != t)...{


p2 = p1;


p1 = p1->next;




if (p2->val < h->val)...{


p2->next = pl;


pl = p2;


}




else...{


p2->next = pr;


pr = p2;


}


}


h->next = quickSortL(pr,t);


return quickSortL(pl,h);


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: