C ++ reverse list

Create a new list is reversed

struct ListNode{
    int val;
    struct ListNode *next;
}

class solution{
public:
    ListNode* ReverseList(ListNode* pHead){
        ListNode* pNode=pHead;     //当前节点
        ListNode* pPrev=nullptr;    //前一个节点
        ListNode* pNext=nullptr;     //后一个节点
        ListNode* pReverseHead=nullptr;    //新链表的头指针
        
        while(pNode!=nullptr){
            pNext=pNode->next;

            if(pNext==NULL)
                 pReverseHead=pNode;
            pNode->next=pPrev;
            pPrev=pNode;
            pNode=pNext;
}
            return pReverseHead;
}
}

Singly linked list reversal (not to establish a new list)

link InvertList(link head){
    link pre,phead,temp;
    phead=head;
    pre=NULL;
    while(phead!=NULL){
        temp=pre;
        pre=phead;
        phead=phead-.next;
        pre->next=templ
}
        return pre;
}

Here Insert Picture Description
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/hj-SAMA/p/12345619.html