题目链接:https://leetcode.com/problems/reverse-linked-list/
题目内容:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目分析:
就是经典的反转链表啦~题目的提示还说用迭代和递归都实现一遍,我只实现了迭代的写法,递归的网上很多,引用其中一位(作者:云中孤鹜)。然后第三种写法是使用栈实现的,虽然消耗多余的空间,但是递归本质上也是一种栈。
递归的写法:
//递归方式
ListNode * ReverseList2(ListNode * head)
{
//如果链表为空或者链表中只有一个元素
if(head==NULL || head->m_pNext==NULL)
return head;
else
{
ListNode * newhead=ReverseList2(head->m_pNext);//先反转后面的链表
head->m_pNext->m_pNext=head;//再将当前节点设置为其然来后面节点的后续节点
head->m_pNext=NULL;
return newhead;
}
}
迭代的写法:
/**
* 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;
else {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur->next != NULL) {
ListNode* pNext = cur->next;
cur->next = pre;
pre = cur;
cur = pNext;
}
cur->next = pre;
return cur;
}
}
};
使用STL栈实现的写法:
/**
* 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;
stack<ListNode*> nodes;
ListNode* lists = head;
while (lists->next != NULL)
{
nodes.push(lists);
lists = lists->next;
}
ListNode* newpHead = lists;
ListNode* newLists = newpHead;
while (!nodes.empty())
{
newLists->next = nodes.top();
newLists = newLists->next;
nodes.pop();
}
newLists->next = NULL;
return newpHead;
}
};