单链表的逆转
利用3个指针遍历单链表,逐个链接点进行反转。
/*
只需要完成逆置链表函数
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL)
{
}
};
*/
class Solution
{
public:
ListNode* ReverseList(ListNode* pHead)
{
if(pHead==NULL||pHead->next==NULL) return pHead;
ListNode*p,*q,*r;
p = pHead;
q = pHead->next;
pHead->next = NULL;
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
pHead=p;
return pHead;
}
};