单链表的反转问题

总是有些笔试会碰到

#include<stdio.h>
#include<stdlib.h>
#define n 5
typedef struct node{
	int num;
	struct node* next;
}*nodelist,node;
int a[n];
nodelist create(int m,int *a)
{
	nodelist L;
	nodelist head;
	int i=0;
	head = (node *)malloc(sizeof(int));
	head->num=0;
	L=head;
	for(i=0; i<n; i++)
	{
		L->next = (node *)malloc(sizeof(int));
		L = L->next;	
		L->num = a[i];
	}
	L->next = NULL;
	return head;
}
void show(nodelist head)
{
	nodelist L=head;
	while(L != NULL)
	{
		printf("%d",L->num);
		L=L->next;	
	}
	printf("\n");
}
//单链表反转
nodelist reverse(nodelist head)
{
	nodelist L=head;
	nodelist pre=NULL;
	nodelist pafter=NULL;
	do{
		pafter = L->next;
		L->next = pre;
		pre = L;
		L = pafter;
	}while(L != NULL);
	return pre;
}
int main()
{
	nodelist list;
	list = (node *)malloc(sizeof(int));
	int i,a[n];
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	list = create(n,a);
	show(list);
	list = reverse(list);
	show(list);
	return 0;
}


你可能感兴趣的:(单链表的反转问题)