反转链表

来源:互联网 发布:什么软件挣钱快好提现 编辑:程序博客网 时间:2024/06/05 04:43

输入一个链表,反转链表后,输出反转链表后头节点

/*struct ListNode { int val; struct ListNode *next; ListNode(int x) :   val(x), next(NULL) { }};*/class Solution {public: ListNode* ReverseList(ListNode* pHead) {        if(pHead==NULL)            return NULL;        if(pHead->next==NULL)            return pHead;               if(pHead->next->next==NULL){            pHead->next->next=pHead;            pHead->next=NULL;        }               ListNode* prev=pHead;        ListNode* temp=pHead->next;        pHead=pHead->next->next;        prev->next=NULL;        while(pHead!=NULL){            temp->next=prev;            prev=temp;            temp=pHead;            pHead=pHead->next;        }               temp->next=prev;        return temp; }};


0 0
原创粉丝点击