[LintCode] Reverse Linked List 倒置链表
Posted Grandyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LintCode] Reverse Linked List 倒置链表相关的知识,希望对你有一定的参考价值。
Reverse a linked list.
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 倒置链表的主要内容,如果未能解决你的问题,请参考以下文章
Lintcode36 Reverse Linked List II solution 题解
Lintcode35 Reverse Linked List solution 题解
[LintCode] Reverse Linked List 倒置链表