剑指offer(12)-反转链表

来源:互联网 发布:机械能守恒实验带数据 编辑:程序博客网 时间:2024/05/18 00:38

题目描述


输入一个链表,反转链表后,输出链表的所有元素。

代码


/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* ReverseList(ListNode* pHead) {        ListNode* pReversedHead = NULL;        ListNode* pNode = pHead;        ListNode* pPrev = NULL;        while (pNode != NULL){            ListNode* pNext = pNode->next;            if(pNext == NULL){                pReversedHead = pNode;            }            pNode->next = pPrev;            pPrev = pNode;            pNode = pNext;        }        return pReversedHead;    }};
0 0