链表反转 -- 剑指OfferC++ Class

    xiaoxiao2021-03-25  152

     

    链表反转 -- 剑指Offer  C++ Class

     

     

    题目描述

    输入一个链表,反转链表后,输出链表的所有元素。

     

    ListNode* reverseList(ListNode* head) { if(head==NULL || head->next==NULL) return head; ListNode *newHead=reverseList(head->next); head->next->next=head; head->next=NULL; return newHead; }

     

    不多说看代码:

     

     

    #include<iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* ReverseList(ListNode* pHead) { /** A->B->C->D A A->NULL prev A B->A prev = B C->B prev = C D reverseHead = D **/ ListNode* reverseHead = NULL; // 需要预先定义一个节点 ListNode* pNode = pHead; //原先节点 ListNode* pPrev = NULL; //原先节点 while(pNode != NULL){ ListNode* pNext =pNode->next; // 原先下一个节点 if(pNext == NULL){ reverseHead = pNode; //如果原先下一个节点是空,那么这个就是新链表的节点 } pNode->next = pPrev; //新链表的下一个节点就是之前节点 pPrev = pNode; pNode = pNext; } return reverseHead; } }; int main(){ ListNode* n1 = new ListNode(1); ListNode* n2 = new ListNode(2); ListNode* n3 = new ListNode(3); ListNode* n4 = new ListNode(4); ListNode* n5 = new ListNode(5); ListNode* n6 = new ListNode(6); n1->next= n2; n2->next = n3; n3->next = n4; n4->next = n5; n5->next = n6; n6->next = NULL; Solution S; ListNode *head = S.ReverseList(n1); while(head != NULL){ cout<<head->val<<endl; head = head->next; } return 0; }

     

     

     

     

     

     

    wangxiaoming 认证博客专家 架构 Spring Boot Redis 博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
    转载请注明原文地址: https://ju.6miu.com/read-2385.html

    最新回复(0)