面试题24:反转链表

考察链表的操作,将单向链表反转,返回头节点。

C++版

#include <iostream>
#include <algorithm>
using namespace std;

// 定义链表
struct ListNode{
    int val;
    struct ListNode* next;
    ListNode(int val):val(val),next(nullptr){}
};

// 反转链表
ListNode* reverseList(ListNode* pHead){
    // 定义反转后的链表的头节点
    ListNode* pReverseHead = nullptr;
    // 定义当前遍历到的节点
    ListNode* pNode = pHead;
    // 定义前一个节点
    ListNode* pPrev = nullptr;
    while(pNode != nullptr){
        ListNode* pNext = pNode->next;
        // 当走到最后时
        if(pNext == nullptr)
            pReverseHead = pNode;
        pNode->next = pPrev;
        pPrev = pNode;
        pNode = pNext;
    }
    return pReverseHead;
}

int main()
{
    char *p = "hello";
    // p[0] = 'H';
    cout<<p<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/flyingrun/p/13377890.html