您的位置:首页 > 其它

无头单链表逆序(法二)

2013-02-27 09:16 197 查看
#include "stdio.h"
#include "stdlib.h"
#include "time.h"

typedef struct node{
int a;
struct node* next;
}LNODE;

LNODE* LinklistCreate(void);
void LinklistVisit(LNODE *head);
LNODE* LinklistConvert(LNODE *);

int main(void)
{
LNODE *head = NULL;

head = LinklistCreate();
if(head == NULL)
return -1;

printf("before convert:\n");
LinklistVisit(head);

head = LinklistConvert(head);

printf("after convert:\n");
LinklistVisit(head);

return 0;
}

LNODE* LinklistCreate(void)
{
int num = 0,i = 0;
LNODE *head = NULL,*pf = NULL,*pb = NULL;
printf("How many nodes do you want?\n");
scanf("%d",&num);
if(num < 1)
return NULL;
for(i = 0;i < num;i++)
{
pf = (LNODE*)malloc(sizeof(LNODE));
if(pf == NULL)
{
if(i == 0)
return NULL;
else
{
for(;i > 0;i--)
{
pf = head->next;
free(head);
head = pf;
}
return NULL;
}
}
if(i == 0)
{
head = pf;
pb = pf;
}
else
{
pb->next = pf;
pb = pf;
}
}
pf->next = NULL;
srand(time(NULL));
pf = head;
do{
pf->a = rand()%100;
}while(pf = pf->next);

return head;
}

void LinklistVisit(LNODE *head)
{
if(head == NULL)
return ;
do{
printf("%d\n",head->a);
}while(head = head->next);
}

LNODE* LinklistConvert(LNODE *head)
{
LNODE *pf = NULL,*tail = NULL;
LNODE *newhead = NULL;
if(head == NULL)
return NULL;
while(tail != head)
{
pf = head;
while(pf->next != tail)
pf = pf->next;
if(tail == NULL)
newhead = pf;
else
tail->next = pf;
tail = pf;
}
tail->next = NULL;
return newhead;
}

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