欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单向链表节点的逆序反转

程序员文章站 2022-03-15 17:36:26
...
#include <stdio.h>

typedef struct node{
	int val;
	struct node *next;
}node;

void reverse(node * pHead)
{
	node * pCur, * pNewHead, * pTemp;
	
	if(NULL == pHead || NULL == pHead->next)
		return;
	
	pNewHead = pHead;
	pCur = pHead->next;
	while(pCur != NULL)
	{
		pTemp = pCur->next;
		pCur->next = pNewHead;
		pHead->next = pTemp;
		pNewHead = pCur;
		pCur = pTemp;
	}
}
int main(void)
{
	char i = 0;
	node buffNode[10] =  {0};
	for(i = 0; i < 9; i++)
	{
		buffNode[i].val = i;
		buffNode[i].next = &buffNode[i+1];
	}
	buffNode[9].val = 9;
	reverse(buffNode);
	//....................验证
	for(i = 0; i < 10; i++)
	{
		printf("%d",buffNode[i].val);
		if(buffNode[i].next != NULL)
		{
			printf(" -> ");
			printf("%d\n",buffNode[i].next->val);
		}
		else
		{
			printf(" -> NULL\n");
		}
	}

	return 0;
}