题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead) {
if (pHead == NULL || pHead->next == NULL) {
return pHead;
}
struct ListNode* pre = NULL;
struct ListNode* cur = pHead;
struct ListNode* next = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
用三指针来翻转链表,空间尺度为O(1),时间尺度为O(n)遍历查找
- 初始化三个指针pre、cur、next,分别指向前一个节点、当前节点和下一个节点。初始化时,pre指向NULL,cur指向头结点pHead。
- 进入循环,遍历链表。在循环中,首先将next指针指向cur的下一个节点,用于保存下一个节点的位置。
- 然后将cur的next指针指向pre,将当前节点的指针反向,完成节点的反转操作。
- 将pre指针指向cur,cur指针指向next,继续遍历链表直到cur为空。
- 最后将pre指向的节点作为新链表的头结点返回。
