leetcode 206-- flipped list
Subject description:
Reverse a singly linked list.
Example:
Input: 1-> 2-> 3-> 4- > 5-> NULL
Output: 5-> 4-> 3-> 2- > 1-> NULL
Advanced:
You may iteratively or recursively inverted list. Can you solve this question in two ways?
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/reverse-linked-list
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Submit a: Iteration
/**
* 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;
}
};
Submit two: this iteration is also quite interesting (excerpt from leetcode official problem-solving)
/**
* 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;
}
};
Submission: the magic of recursion
/**
* 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;
}
};
Problem Solving: leetcode official problem-solving: