码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 206 Reverse Linked List

时间:2016-09-06 13:57:33      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

Reverse a singly linked list.

 

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

题目大意:反转单链表

提示:

反转一个链表可以用迭代或者递归的方法。你能都实现吗?

 

递归:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         //最后一个节点会返回,作为头结点
13         if(head == NULL || head -> next == NULL)
14             return head;
15         //head->next 表示剩下的部分
16         ListNode* newHead = reverseList(head -> next);
17         head -> next -> next = head;
18         head -> next = NULL;
19         return newHead;
20     }
21 };

迭代:

 

Leetcode 206 Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/qinduanyinghua/p/5845248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!