OJ lintcode 翻转链表

翻转一个链表
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一个链表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.
     */
    void  insert(ListNode * newhead,ListNode * node){
        ListNode * q = newhead->next;
        newhead->next=node;
        node->next=q;
    }
    ListNode *reverse(ListNode *head) {
        // write your code here
        if(head==NULL){
            return NULL;
        }
        if(head->next==NULL){
            return head;
        }

        ListNode * newhead=new ListNode();
        newhead->next=head;
        ListNode * p=head->next;
        head->next=NULL;

        while(p!=NULL){
            ListNode * node =p;
            p=p->next;
            insert(newhead,node);
        
        }
        return newhead->next;
    }
};

你可能感兴趣的:(OJ lintcode 翻转链表)