题目链接:翻转链表
C++题解:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
思路:
利用双指针,从前往后,不断的将前后两个顶点的指向掉转。
算法复杂度:
时间复杂O(n)
空间复杂度O(1)