//#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]#206 Reverse Linked List
最新推荐文章于 2024-09-08 20:02:08 发布