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

leetcode 206. Reverse Linked List

时间:2016-04-25 06:39:52      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

题意:把一个链表倒过来。

题解:有递归和非递归两种方式,主要就是考察指针操作的熟悉程度。

递归的方法:

/**
 * 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) {
        if(!head||!(head->next))return head;
        ListNode* p=reverseList(head->next);
        head->next->next=head;
        head->next=nullptr;
        return p;
    }
};

非递归:就一个一个转过来方向就好了。转的时候需要用两个辅助指针,一个指向该节点的前一个节点,一个指向后一个节点。

/**
 * 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) {
        if(!head||!(head->next))return head;
        ListNode* pre=nullptr;
        ListNode* back=head->next;
        while(back){
            head->next=pre;
            pre=head;
            head=back;
            back=back->next;
        }
        head->next=pre;
        return head;
    }
};

 

leetcode 206. Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/zywscq/p/5429141.html

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