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

Leetcode44: Reverse Linked List

时间:2015-07-03 12:25:02      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

Reverse a singly linked list.

 定义3个相邻的指针,pre、cur、post,每次往后挪一位,将cur的next指向pre,直到post为空。

/**
 * 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 == NULL || head->next == NULL)
            return head;
        
        ListNode* pre = head;
        ListNode* cur = pre->next;
        ListNode* post = cur->next;
        
        pre->next = NULL;
        while(post)
        {
            cur->next = pre;
            pre = cur;
            cur = post;
            post = post->next;
        }
        cur->next = pre;
        return cur;
    }
    
};

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode44: Reverse Linked List

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/u013089961/article/details/46739523

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