标签:
解题思路:三指针,跟踪算法的过程如下:
代码如下:
/**
* 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;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46792363