首页 > 代码库 > [LintCode] Reverse Linked List 倒置链表
[LintCode] Reverse Linked List 倒置链表
Reverse a linked list.
Have you met this question in a real interview?
Yes
Example
For linked list 1->2->3
, the reversed linked list is 3->2->1
Challenge
Reverse it in-place and in one-pass
LeetCode上的原题,请参见我之前的博客Reverse Linked List。
解法一:
class Solution {public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { if (!head) return NULL; ListNode *dummy = new ListNode(-1), *cur = head; dummy->next = head; while (cur->next) { ListNode *t = cur->next; cur->next = t->next; t->next = dummy->next; dummy->next = t; } return dummy->next; }};
解法二:
class Solution {public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { if (!head || !head->next) return head; ListNode *t = head; head = reverse(t->next); t->next->next = t; t->next = NULL; return head; }};
[LintCode] Reverse Linked List 倒置链表
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。