首页 > 代码库 > Link List
Link List
At first, i prepared to go through 《the introduction to algorithm》 ,however , i found some part of the book is difficult to understand; what’s more , i can’t borrow the book in the library. Then i found another book, 《algorithm in C》,which reveal most basic idea of some classical algorithm, so i decide to read this book firstly.
example 1:josephus funciton
#include<stdlib.h>#include<stdio.h>typedef struct node* link;struct node{ int item; link next;};int main(int argc,char *argv[]){ int i, N, M; scanf("%d%d",&N,&M); node *t = new node,*x; x = t; t->item = 1; t->next = t; for (i = 2; i <= N; i++) { x->next = new node; x = x->next; x->item = i; x->next = t; } while (x != x->next) { for (i = 1; i < M; i++) { x = x->next; } x->next = x->next->next; N--; } printf("%d\n",x->item);}
example2: reverse link list
#include<stdlib.h>#include<stdio.h>typedef struct node* link;struct node{ int item; link next; node() { next = NULL; }};link reverse(link x){ /* 将y后节点的指针保存在t中,然后将y的链接指向r,再使r移到y,y移到t */ link t, y = x, r = NULL; while (y != NULL) { t = y->next; y->next = r; r = y; y = t; } return r;}int main(int argc,char *argv[]){ int i, N, M; scanf("%d%d",&N,&M); node *t = new node,*x,*head; x = t; head = t; t->item = 1; t->next = t; for (i = 2; i <= N; i++) { x->next = new node; x = x->next; x->item = i; } node *newhead = reverse(head); while (newhead != NULL) { printf("%d ",newhead->item); newhead = newhead->next; }}
Link List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。