您的位置:首页 > 其它

【LeetCode】206. Reverse Linked List

2015-09-10 16:45 447 查看

题目:

Reverse a singly linked list.

提示:

此题不难,可以用迭代或者递归两种方法求解。记得要把原来的链表头的next置为NULL;

代码:

迭代:

/**
* 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) return NULL;
ListNode *pre = head, *cur = head->next;
pre->next = NULL;
ListNode *tmp;
while (cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};


递归:

/**
* 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) {
return reverseNode(head, NULL);
}

ListNode* reverseNode(ListNode* head, ListNode* newHead) {
if (!head) return newHead;
ListNode *next = head->next;
head->next = newHead;
return reverseNode(next, head);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: