本文主要是介绍206. Reverse Linked List(Leetcode每日一题-2020.03.02),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
Reverse a singly linked list.
Example
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Solution
Solution1
三指针迭代
/*** 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 || !head->next)return head;ListNode* prev = NULL;ListNode* cur = head;ListNode* next = head->next;while(cur){cur->next = prev;prev = cur;cur = next;if(next)next = next->next;}return prev;}
};作者:sxycsjt
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/c-di-gui-san-zhi-zhen-die-dai-by-sxycsjt/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Solution2
递归
/*** 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 || !head->next)return head;ListNode *newHead = reverseList(head->next);//此时head->next就是以head->next为链表头的链表反转后的链表尾head->next->next = head;head->next = NULL;return newHead;}
};
这篇关于206. Reverse Linked List(Leetcode每日一题-2020.03.02)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!