您的位置:首页 > 其它

leetcode 206 Reverse Linked List

2018-02-11 20:57 323 查看
Problem:

单链表转置。

Solution:

1. 利用中间变量保存指针,循环逆置。

2. 递归改变链表指针。

notes:

结束后返回的是新链表的头。

注意处理异常,比如head是空的情况。

利用相同子结构优化冗余逻辑。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode* next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
//Solution1 Iterative
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;

while(curr != NULL) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}

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