您的位置:首页 > 其它

LeetCode 206. Reverse Linked List

2017-08-08 09:27 447 查看

206. Reverse Linked List

Description

Reverse a singly linked list.

Solution

题意即将一个链表倒转。

有两种方式,迭代和递归,代码如下。

// 迭代

class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre = NULL;
while (head) {
ListNode *p = head->next;
head->next = pre;
pre = head;
head = p;
}
return pre;
}
};

// 递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息