Niuke Tiba nc78 reverse linked list C + + problem solution

Time:2021-9-15

Original question link

Meaning:

Same as the title

Solution:

Reversing the linked list (one-way) is to make each element\(next\)Of the element pointed to\(next\)Just come back.

Then create a new pointer to record the previous element for operation.

But there is a small problem with the above operation: it cannot be transferred backward.

Solution: directly open another pointer to record the current element\(next\)Just.

Code (c + +):

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* s;
        ListNode* z = NULL;
        while(pHead != NULL){
            s = pHead ->next;
            pHead ->next = z;
            z = pHead;
            pHead = s;
        }
        return z;
    }
};