链表内指定区间反转:https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
思路如下:
1.首先考虑简单点的场景,
反转整个链表
如果是反转整个链表的话,我们要做的是将原本某个节点的next指向这个节点的前一个节点(将前一个节点记为pre)
对与 [1 -> 2 -> 3 -> 4 -> null] 这个链表来说:
1的pre为null(1节点没有前节点)
2的pre为1
3的pre为2
4的pre为3
因此,对于每个节点我们必须要知道它的pre。我们在遍历链表的时候就不断将当前的节点更新给pre,那么对与当前节点的next来说,pre就是已知的了。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre = NULL;
while(pHead){
ListNode *temp = pHead