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

[LeetCode]206. Reverse Linked List 解题小结

时间:2016-09-04 17:37:14      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

用循环来做

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
/**
 * Reverse Iteratively
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* revHead = NULL;
        ListNode* rev = head;
        
        while(rev){
            head = rev;
            rev = rev->next;
            head->next = revHead;
            revHead = head;
        }
        
        return revHead;
        
    }
};

用递归来做:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
/**
 * Reverse Iteratively
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        
        if(!head || (!head->next))return head;
        ListNode* node = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return node;
        
    }
};

 

[LeetCode]206. Reverse Linked List 解题小结

标签:

原文地址:http://www.cnblogs.com/Doctengineer/p/5839720.html

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