题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
// write code here
if(pHead == NULL)
{
return NULL;
}
struct ListNode* p = NULL;
struct ListNode* q = pHead->next;
//pHead->next是在变化的,操作完成后就指向前方了,所以退不出循环
//所以要用q来作为pHead->next的替代
//故在循环的判断条件中,参数在不断变化的话,要用另一个参数替代他
while(q != NULL)
{
p = pHead;
pHead = q;
q = q->next;
if(1 == p->val)
{
p->next = NULL;
}
pHead->next = p;
}
return pHead;
}
爱玛科技公司福利 8人发布