leetcode 206 Reverse Linked List

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;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/cfarmerreally/article/details/79313212