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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容