题目描述
反转链表
样例
依次遍历节点,记录这个节点cur的下一个节点next;更新pre, cur
反转:把cur的next指针指向pre
blablabla
算法
时间复杂度
O(N)
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
ListNode* nextNode = cur->next;
cur->next = pre;
pre = cur;
cur = nextNode;
}
return pre;
}
};