题目描述
输入一个链表,反转链表后,输出链表的所有元素。
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead){ if(!pHead)//头结点为空 return nullptr; ListNode *p=pHead; ListNode *q=p->next; ListNode *r=nullptr; if(q)//链表至少有两个结点 r=q->next; p->next=nullptr; while(q){ q->next=p; p=q; q=r; if(r) r=r->next; } pHead=p; return pHead; } };