剑指offer-反转链表C++实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* head) {
cur = head;
// 当前结点不为空时,遍历链表
while(cur!=nullptr){
// 找到当前结点的后继结点
nex = cur->next;
// 当前结点next指针指向它的前驱结点
cur->next = pre;
// pre移到当前结点的位置
pre = cur;
// cur移到nex结点的位置
cur = nex;
}
return pre;
}
private:
ListNode *cur = nullptr;
ListNode *nex = nullptr;
ListNode *pre = nullptr;
};
思路:
这是一道链表入门题,考察的是对链表的掌控,设置三个指针pre,cur,nex,其中pre指向前驱结点,cur指向当前结点,nex指向cur的后继结点。改变当前指针的后继结点不断指向前驱结点即可,注意头结点反转之后是尾结点,尾结点next指针指向空。
时间复杂度O(n),空间复杂度O(1)