[置顶] 链表逆转(递归+非递归)

将链表逆转

//非递归
/**
 * 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 == NULL)
            return NULL;
        ListNode *p,*q;
        p = head->next;
        head->next = NULL;
        while (p != NULL)
        {
            q = p->next; //保存p的后续节点
            p->next = head;
            head = p;
            p = q;
        }
        return head;
    }
};

递归版本

// Recursive
ListNode* reverseList(ListNode* head)
{
    if(head==NULL||head->next==NULL)
    return head; // head->next==NULL is the base case for recursion
    ListNode* nex = head->next;
    head->next=NULL;
    ListNode* newHead = reverseList(nex);
    nex->next=head;
    return newHead;
}


你可能感兴趣的:(算法,链表)