剑指offer-----反转链表

题目:

输入一个链表,反转链表后,输出反转链表的头结点。

链接:

剑指Offer:16题

思路标签:

  • 数据结构:链表

解答:

1. C++

/*
struct Listnode
{
	int value;
	struct Listnode *next
}
*/

Listnode* REverseList(Listnode* phead)
{
	//判断
	if (phead==NULL || phead->next==NULL)
		return phead;
		
	Listnode* pNew=NULL;
	Listnode* pNode=phead;
	
	while(pNode != NULL)
	{
		Listnode* temp=pNode->next;//保存下一个位置
		
		if(temp==NULL)
			pNew=pNode;
		
		pNode->next=pNew;   //将pNew接在第一个节点后面
		pNew=pNode;        //将phead设置为新链表的头部
		
		pNode=temp;    //寻找下个位置
	}
	
	return pNew;
}
		

参考资料:《剑指offer》

猜你喜欢

转载自blog.csdn.net/qq_39503189/article/details/82117492