您的位置:首页 > 其它

[Leetcode]#206 Reverse Linked List

2015-09-02 07:59 405 查看
//#206 Reverse Linked List
//8ms 100%
#include <iostream>
using namespace std;

class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
ListNode *previous_p, *current_p, *next_p;
if(head == NULL) return head;           //linked_list size == 0
if(head->next == NULL) return head;     //linked_list size == 1
if(head->next->next == NULL)            //linked_list size == 2
{
head->next->next = head;
head = head->next;
head->next->next = NULL;
return head;
}

//linked_list size >= 3
previous_p = head;
current_p = head->next;
next_p = head->next->next;

previous_p->next = NULL;
while(next_p->next != NULL)
//next_p reaching the tail and when jumping out of this while loop
//next_p->next == NULL
{
current_p->next = previous_p;

//prepare for next round
previous_p = current_p;
current_p = next_p;
next_p = next_p->next;
}

current_p->next = previous_p;
next_p->next = current_p;
head = next_p;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode linkedlist