题目:
Reverse a singly linked list.
题意:
反转单链表。
思路:
可以使用循环的方式,或者栈的方式,或者递归。
栈的方式是把每个元素依次入栈,出来的时候就是从尾到头的顺序。
递归的本质就是栈,此处不表。
代码如下:
注释部分是循环和栈的两个实现。
/**
* 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)return NULL;
ListNode* tail = NULL;
return reverseList(head, tail);
/*ListNode* last = NULL;
ListNode* next = NULL;
while(head != NULL)
{
next = head->next;
head->next = last;
last = head;
head = next;
}
return last;*/
/*stack<ListNode* > s;
while(head != NULL)
{
s.push(head);
head = head->next;
}
ListNode* result = s.top();
ListNode* h = result;
s.pop();
while(!s.empty())
{
ListNode* tmp = s.top();
s.pop();
result->next = tmp;
result = tmp;
}
result->next = NULL;
return h;
*/
}
ListNode* reverseList(ListNode* head, ListNode* & tail)
{
if(head->next == NULL)
{
tail = head;
tail->next = NULL;
return head;
}
ListNode* result = reverseList(head->next, tail);
tail->next = head;
tail = head;
tail->next = NULL;
return result;
}
};