翻转链表-LintCode

来源:互联网 发布:淘宝关键词热度 编辑:程序博客网 时间:2024/05/21 14:52

描述:

翻转一个链表。

样例:

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null


思路:

新建一个链表,把给出链表的节点利用头插法插入新链表,就得到了翻转的链表。

/** * 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) {        // write your code here        ListNode *r=new ListNode(0);                while(head!=NULL)        {            ListNode *temp=new ListNode(0);            temp->val=head->val;            temp->next=r->next;            r->next=temp;            head=head->next;                              }        return r->next;    }};




0 0
原创粉丝点击