C++反转链表

建立新链表进行反转

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;
}
}

单链表反转(不建立新的链表)

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;
}

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自www.cnblogs.com/hj-SAMA/p/12345619.html