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;
    }
};

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容