Prove safety offer 16: reverse list

Title Description

After entering a list inverted list, the new list of the output header.

Problem-solving ideas

Single list situ reversal is very classic interview Shredded code is part of a problem. For general single list, the reverse operation is required when the current node and two other adjacent thereto. Thereby to define three temporary node pointer pointing variation.

A very important principle: we must ensure the robustness of the code. (NULL test, the list of cross-border inspection etc., etc., the more simple the code, the test code base foundation)

C ++ code to achieve:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *p=NULL,*q=pHead,*tmp=NULL;
        while(q!=NULL){
            tmp=q->next;
            q->next=p;
            p=q;
            q=tmp;
        }
        if(pHead!=NULL){  // PHEAD pointing whole has not been operated, when the reverse is the completion point of the latter (previously a) node, the end node is set to the need for timely NULL; 
            pHead-> Next == NULL; 
        } 
        PHEAD = P ;
        return PHEAD; 
    } 
};        

 

Guess you like

Origin www.cnblogs.com/fancy-li/p/11616019.html