leetcode反转链表

题目描述:

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:

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

再简单的题目也要亲自动手做一下,给出递归和非递归的方法:

//递归方法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode * newh = NULL;
        ListNode * next = NULL;
        if (head == NULL || head->next == NULL)
        {
            return head;
        }
        next = head->next;
        newh = reverseList(next);
        next->next = head;
        head->next = NULL; //一定要置NULL,我就因为这调试了老半天
        return newh;
        
    }
};
//非递归方法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = NULL;
        ListNode *cur = NULL;
        ListNode *next = NULL;
        if (head == NULL)
        {
            return NULL;
        }
        cur = head;
        next= head->next;
        head->next = NULL;
        while(next != NULL)
        {
            pre = cur;
            cur = next;
            next = cur->next;
            cur->next = pre;
        }
        return cur;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_39750703/article/details/85240809
今日推荐