#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
typedef struct list
{
int num;
struct list* next;
}LIST;
void init_list(LIST** L)
{
*L = (LIST*)malloc(sizeof(LIST));
(*L)->next = NULL;
}
void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int getrand(int A[], int start, int end)
{
int nums = end - start + 1;
int location = rand()%nums + start;
swap(A+start,A+location);
return A[start];
}
void add_list(LIST* L, int num)
{
LIST* p = L->next;
LIST* q = L;
while(p!=NULL)
{
q = p;
p = p->next;
}
p = (LIST*)malloc(sizeof(LIST));
p->num = num;
p->next = NULL;
q->next = p;
}
void print_list(LIST* L)
{
int count = 0;
LIST* p = L->next;
while(p!=NULL)
{
if(++count%5 == 0)
printf("%d\n",p->num);
else
printf("%d\t",p->num);
p = p->next;
}
}
LIST* count_lask_k_node(LIST* L, int k)
{
int i = 0;
LIST* p = L->next;
LIST* q = L->next;
for(;i<k;i++)
q = q->next;
while(q!=NULL)
{
p = p->next;
q = q->next;
}
return p;
}
int main(int argc, char *argv[])
{
int i = 0;
int num;
int k = 0;
int A[N] = {1,2,3,4,5,6,7,8,9,10};
LIST* L = NULL;
init_list(&L);
for(; i<N; i++)
{
num = getrand(A,i,N-1);
add_list(L,num);
}
printf("the list is:\n");
print_list(L);
//k = rand()%N+1;
k = 1;
LIST* ret = count_lask_k_node(L,k);
printf("the last %d node is %d\n",k,ret->num);
system("PAUSE");
return 0;
}
|