Reverse a singly linked list.
题目大意:反转一个单链表~
分析:设立三个指针:cur——当前结点;pre——当前结点的前一个结点;temp——临时结点(标记cur的next)。首先保存cur的next到temp,然后将cur的next指向pre,将pre移动到当前cur,然后将cur指向temp,直到cur==NULL,返回pre即反转了该链表~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Solution { public: ListNode* reverseList(ListNode* head) { if (head == NULL) return head; ListNode *cur = head, *pre = NULL, *temp = NULL; while (cur != NULL) { temp = cur->next; cur->next = pre; pre = cur; cur = temp; } return pre; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼