单链表逆序(C语言)

单链表逆序(C语言)

#include"stdio.h" 
#include"stdlib.h"

typedef struct node
{
	int val;
	struct node *next;
}Node,*pNode;

pNode Creatlist()
{
	int cnt,i,val; 
	pNode pHead = NULL;
	pHead = (pNode) malloc(sizeof(Node));
	
	pNode pTail = pHead;
	printf("请输入节点的个数:\n");
	scanf("%d",&cnt);
	for(i=1;i<=cnt;i++)
	{
		printf("请输入第%d节点的值\n",i);
		scanf("%d",&val);
		pNode pNew;
		pNew = (pNode) malloc(sizeof(Node));
		
		pNew->val = val;
		
		pTail->next = pNew;
		pTail = pNew;
		pNew->next = NULL;
	}
	return pHead;
}

void Traversallist(pNode pHead)
{
	int i = 1;
	pNode p = pHead->next;
	while(p != NULL)
	{
		printf("第%d个节点的值为%d\n",i,p->val);
		p = p->next;
		i++;
	}
}
pNode Reverselist(pNode pHead)
{
	pNode p,q,pr;
	p = pHead->next;
	q = NULL;
	pHead->next = NULL;
	while(p != NULL)
	{
		pr = p->next;
		p->next = q;
		q = p;
		p = pr;
	}
	pHead->next = q;
	return pHead;
}
int main()
{
	pNode pHead = NULL;
	pHead = Creatlist();
	Traversallist(pHead);
	printf("\n");
	pHead = Reverselist(pHead);
	Traversallist(pHead);
	return 0;
}

 

你可能感兴趣的:(单链表逆序(C语言))