leetcode 206——翻转链表
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提交一:迭代
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//迭代法翻转链表
//将首节点pMove的后面节点nextNode拿到头部 head
//重复这一过程,直到原来的首结点pMove移动到尾节点
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr) return head;
ListNode* pMove = head;
while(pMove->next){//当pMove没有到达尾节点时迭代进行(循环)
ListNode* nextNode = pMove->next; //将pMove->next得到
//将nextNode拿到头结点
pMove->next = nextNode->next;
nextNode->next = head;
head = nextNode;
}
return head;
}
};
提交二:这样迭代也挺有意思(摘自leetcode官方解题)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 4 -> 3 -> 7 -> 9 -> nullptr
//nullptr <- 9 <- 7 <- 3 <- 4
//将当前结点curNode的指向由指向右边改为指向左边
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* frontNode = nullptr;
ListNode* curNode = head;
while(curNode){
ListNode* nextNode = curNode->next;
curNode->next = frontNode;
frontNode = curNode;
curNode = nextNode;
}
return frontNode;
}
};
提交:神奇的递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}![在这里插入图片描述](https://img-blog.csdnimg.cn/20200210161921279.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDc5NTgzOQ==,size_16,color_FFFFFF,t_70)
* };
*/
//神奇的递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr) return head;
ListNode* headNode = reverseList(head->next);
head->next->next = head;
head->next =nullptr;
return headNode;
}
};
解题:leetcode官方解题: