单链表的逆置

这种基础题面试时经常碰到,昨天去面试的时候。又碰到了。这种题目要一次性写出来,不能有一点bug。


struct ListNode
{
	ListNode *next;
	int data;
};

ListNode* reverse(ListNode *head)
{
	ListNode *p = head, *pre = nullptr, *rev_head = nullptr;
	while (p)
	{
		ListNode *pNext = p->next;
		if (p->next == nullptr)
			rev_head = p;
		p->next = pre;
		pre = p;
		p = pNext;
	}
	return rev_head;
}


你可能感兴趣的:(单链表的逆置)