LeetCode:Reverse Linked List

问题描述:Reverse a singly linked list.顾名思义,就是将单链表反转,这其实一道很简单的算法,我在前面的博客也写过解法,以前是刚看过《剑指offer》,所以对那上面的解法印象较深。

解法一:

参考代码如下:

结构体定义:

struct NodeList
{
    int value;
    struct NodeList  next;
};
函数实现:
NodeList *ReverseList(NodeList * pHead)
{
    NodeList * pNode = pHead;
    NodeList * pPrev = NULL;
    NodeList * pReverseHead = NULL;
    while(pNode != NULL)
    {
        NodeList *pNext = pNode->next;
        if(pNext == NULL)
        {
                 pReverseHead = pNode;
        }
        pNode->next = pPrev;
        pPrev = pNode;
        pNode = pNext;        
    }
    return pReverseHead;
}
今天又刷到这道题目,这次是用头插法实现。

解法二:

/**
 * 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|| head -> next == NULL)
        return head;
    ListNode* pPre = head;
    ListNode* pCurrent = head -> next;
    pPre -> next = NULL;
    while(pCurrent)
    {
        ListNode* pNext = pCurrent -> next;
        if(pCurrent -> next == NULL)
        {
            pCurrent -> next = pPre;
            return pCurrent;
        }
        pCurrent -> next = pPre;
        head = pCurrent;
        pPre = pCurrent;
        pCurrent = pNext;
    }
    return head;
   }
};


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