反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
方法一:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack<int> save;
while(head)
{
save.push(head ->val);
head = head ->next;
}
ListNode *newHead = NULL;
ListNode *lastNode = NULL;
while(!save.empty())
{
if(newHead == NULL)
{
newHead = new ListNode(save.top());
lastNode = newHead;
}
else
{
ListNode *temp = new ListNode(save.top());
lastNode ->next = temp;
lastNode = lastNode ->next;
}
save.pop();
}
return newHead;
}
};
方法二:
链表反转后,实际上只是中间节点的指针反转
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* rHead = NULL; // 反转后的头节点
ListNode* curr = head; // 当前处理节点
ListNode* pTail = NULL; // 反转后尾节点
while(curr != NULL) {
ListNode* pNext = curr ->next;
if(pNext == NULL)
rHead = curr;
curr ->next = pTail;
pTail = curr;
curr = pNext;
}
return rHead;
}
};
递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* rHead = reverseList(head->next); // 反转得到新链表的头节点
head->next->next = head; // 当前节点的下一个节点的next指针反转过来
head->next = NULL; // 设置新链表的尾节点
return rHead;
}
};