单向链表翻转

Posted veis

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向链表翻转相关的知识,希望对你有一定的参考价值。

#include <stdio.h>
#include <stdlib.h>

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

ListNode* ReverseList(ListNode* pHead)
{
	if (pHead == NULL)
		return pHead;
	ListNode* pre = NULL;
	ListNode* cur = pHead;
	ListNode* nxt = NULL;
	ListNode* res = NULL;
	while (cur != NULL)
	{
		nxt = cur->next;
		cur->next = pre;
		if (nxt == NULL)
			break;

		pre = cur;
		cur = nxt;
	}
	return cur;
}

int main()
{
	int i = 0;
	ListNode *pHead = NULL;
	while (i <= 5)
	{
		ListNode *pNew = (ListNode *)malloc(sizeof(ListNode));
		pNew->val = i++;
		pNew->next = pHead;
		pHead = pNew;
	}
	pHead = ReverseList(pHead);

	while (pHead)
	{
		printf("%d ", pHead->val);
		pHead = pHead->next;
	}
	system("pause");
	return 0;
}

  

以上是关于单向链表翻转的主要内容,如果未能解决你的问题,请参考以下文章

单向链表的构建以及翻转算法_图文详解

Java 单向链表翻转

Java 单向链表翻转

单向链表翻转

C语言反转单向链表的代码

剑指 Offer 06. 从尾到头打印链表难度:简单(链表翻转)