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

Reverse Linked List

时间:2015-07-07 19:30:05      阅读:106      评论: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) {
        ListNode *p;
        p = head;
        int counter = 0;
        for(; p != NULL; ) {
            counter++;
            p = p->next;
        }

        if(counter == 0) {
            return NULL;
        }

        if(counter == 1) {
            return head;    
        }

        if(counter == 2) {
            ListNode *p21, *p22;
            p21 = head;
            p22 = p21->next;
            p21->next = NULL;
            p22->next = p21;
            return p22;
        }

        ListNode *p1, *p2, *p3;
        p1 = head;
        p2 = head->next;
        p3 = head->next->next;
        head->next = NULL;
        for(; p3 != NULL; ) {
            p2->next = p1;
            p1 = p2;
            p2 = p3;
            p3 = p3->next;
        }
        p2->next = p1;
        return p2;




    }
};

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

Reverse Linked List

标签:

原文地址:http://blog.csdn.net/guanzhongshan/article/details/46792363

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