题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
解题思路:
解题注意点:空间复杂度O(1),
1、判空
2、在改变指针指向方向改变前存储好下个节点的位置
/** * 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* tmp=NULL; //将要被指向的节点 struct ListNode* ret = pHead; //改变节点指向方向的指针 while(pHead->next!=NULL){ pHead = pHead->next; //存储下一个节点的位置 ret->next = tmp; tmp = ret; ret = pHead; } pHead->next = tmp; //循环结束后头节点指向方向需改变 return pHead; }