反转一个单链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public://迭代
   /* ListNode* reverseList(ListNode* head) { 
        //ListNode* tmp;
        if(!head) return NULL;
        ListNode* headp = new ListNode(head->val);
    //    head->val = head->val;
        
        ListNode* p = head->next;
        while(p){
          ListNode* tmp = new ListNode(p->val);
          //tmp = p.val;
          tmp->next = headp;
          headp = tmp;
          p = p->next;
            //tmp->next = p;             
        }
        ListNode* p2 = headp;
        while(p2){
            cout << p2->val << ",";
            p2 = p2->next;
        }
        return headp;        
    }*/
    
    ListNode* reverseList(ListNode* head){
        if(!head) return NULL;
        ListNode  *reversed = NULL;
        getReversed(head,&reversed);
        return reversed;
        //if(ListNode)        
        
    }//递归
    void getReversed(ListNode* head, ListNode** reversed){
        if(head->next == NULL){
            head->next = *reversed;            
            *reversed = head;
        } else {
            ListNode* tmp = new ListNode(head->val);
            tmp->next = *reversed;
            *reversed = tmp;
            getReversed(head->next, reversed);
        }        
    }
        
};

 

posted @ 2019-08-30 16:00  卷积  阅读(217)  评论(0编辑  收藏  举报