王道p40 3.设L为带头结点的单链表,编写算法实现从头到尾反向输出每个结点的值

本题代码为

void nizhi(linklist* L)//逆置
{
	lnode* p = (*L)->next, * pre = *L;
	lnode* r = p;
	(*L)->next = NULL;
	while (p != NULL)
	{
		p = p->next;
		r->next = (*L)->next;
		(*L)->next = r;
		r = p;
	}
}

完整测试代码

#include
#include
typedef struct lnode
{
	int data;
	struct lnode* next;
}lnode,*linklist;
int n = 4;
int a[4] = { 1,2,3,4 };
void buildlinklist(linklist* L)
{
	*L = (lnode*)malloc(sizeof(lnode));
	(*L)->next = NULL;
	lnode* s = *L, * r = *L;
	int i = 0;
	for (i = 0; i < n; i++)
	{
		s = (lnode*)malloc(sizeof(lnode));
		s->data = a[i];
		s->next = r->next;
		r->next = s;
		r = s;
	}
	r->next = NULL;
}
void nizhi(linklist* L)
{
	lnode* p = (*L)->next, * pre = *L;
	lnode* r = p;
	(*L)->next = NULL;
	while (p != NULL)
	{
		p = p->next;
		r->next = (*L)->next;
		(*L)->next = r;
		r = p;
	}
}
void print(linklist* L)//输出单链表
{
	lnode* p = (*L)->next;
	while (p != NULL)
	{
		printf("%d ", p->data);
		p = p->next;
	}
}
int main()
{
	linklist L;
	buildlinklist(&L);
	printf("原先单链表为:");
	print(&L);
	nizhi(&L);
	printf("\n逆置后的单链表为:");
	print(&L);
	return 0;
}

你可能感兴趣的:(王道课后习题单链表,算法,c语言,数据结构)