码迷,mamicode.com
首页 > 其他好文 > 详细

reverse list

时间:2015-09-04 21:09:32      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

解法1:

/**
 * 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* p = head;
        ListNode* newHead = NULL;
        while (p){
            
            ListNode* t = p->next;
            p->next = newHead;
            newHead = p;
            p = t;
        }
        return newHead;
    }
};

解法2:递归

/**
 * 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
        if (head == NULL || head->next == NULL)
            return head;
        ListNode* newHead = reverse(head->next);
        head->next->next = head;
        head->next = NULL;
        return newHead;
    }
};

 

reverse list

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4782258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!