Lintcode翻转链表

来源:互联网 发布:剑灵龙族男捏脸数据 编辑:程序博客网 时间:2024/05/18 00:06

翻转链表

/** * Definition of ListNode *  * class ListNode { * public: *     int val; *     ListNode *next; *  *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @return: The new head of reversed linked list.     */    ListNode *reverse(ListNode *head) {        if(head==NULL){            return NULL;        }        //初始化newList,temp        ListNode *newList=new ListNode(head->val);        ListNode *temp=new ListNode(0);        //依次将list的第一个结点放到newList的第一个结点位置        while(head->next!=NULL){            temp=newList;    //保存newList中的后继结点            newList=head->next;  //将head的第一个结点放到newList中            head->next=head->next->next;//从head中删除摘除这个结点            newList->next=temp;//恢复newList中后继结点的指针        }        //原头结点应该释放掉,并返回新头结点的指针        delete head;        return newList;    }};
原创粉丝点击