剑指offer 15:反转链表

#include <iostream>


using namespace std;

struct ListNode
{
public:
    int val;
    struct ListNode *next;
};

class Solution
{
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *pReversedHead = NULL;
        ListNode *pNode = pHead;
        ListNode *pPrev = NULL;
        ListNode *pNext = NULL;
        while (pNode != NULL) {
            pNext = pNode->next;//保存其下一个节点
            pNode->next = pPrev;//指针指向反转
            pPrev = pNode; // 保存前一个指针
            pNode = pNext; //递增指针,指向下一个节点
        }

        return pPrev;//pPrev指针指向的那个节点就是原来的末指针,新的头指针

    }




};



int main()
{
    ListNode list[4];
    list[0].val = 1;
    list[0].next = &list[1];

    list[1].val = 2;
    list[1].next = &list[2];

    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = NULL;

    ListNode *node = list;
    while (node != NULL) {
        cout << node->val << endl;
        node = node->next;
    }

    Solution solu;


    node = solu.ReverseList(list);
    while (node != NULL) {
        cout << node->val << endl;
        node = node->next;
    }

    return 0;
}


猜你喜欢

转载自blog.csdn.net/liufanlibashanxi/article/details/85345529