Link List

时间:2023-03-09 23:57:29
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;
}
}