Niuke.com brush questions | reverse linked list

Topic source: Niuke.com
programming link

Topic description:

Input a linked list, after reversing the linked list, output all elements of the linked list.

Parse:

The reverse list mainly examines the familiarity with the list, and there are two ways of writing it: recursive and non-recursive;

Recursive code:

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == nullptr||pHead->next == nullptr)  //递归退出条件,就是出现空指针
            return pHead;
        auto pre = ReverseList(pHead->next);   //反转到最后一个
        pHead->next->next = pHead;      对于每一个被反转的节点,
        pHead->next = nullptr;
        return pre;
    }
};

looping code:

class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* ReverseHead = NULL;
        ListNode* pNode = pHead;
        ListNode* pPre = NULL;
        while(pNode!=NULL)
        {
            ListNode* temp = pNode->next;
            if(temp==NULL)
                ReverseHead=pNode;
            pNode->next = pPre;
            pPre = pNode;
            pNode = temp;
        }
        return ReverseHead;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568205&siteId=291194637