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

来源:互联网 发布:visio数据库模型图 编辑:程序博客网 时间:2024/06/10 20:33

代码实现:

#include <stdio.h>#include <iostream>#include <vector>using namespace std;struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};class Solution {public:    ListNode* ReverseList(ListNode* pHead) {        ListNode* pNewHead = pHead;        ListNode* pNodeNext = pHead->next;        ListNode* pNodePre = pHead;        if(pHead == NULL)        {            return NULL;        }        pNewHead->next = NULL;        while(1)        {            if(pNodeNext == NULL)            {                break;            }            pNodePre = pNewHead;            pNewHead = pNodeNext;            pNodeNext = pNodeNext->next;            pNewHead->next = pNodePre;        }        return pNewHead;    }};int main(){    ListNode* head = NULL;    ListNode* temp = NULL;    ListNode* newNode = NULL;    int i = 0;    Solution s;    head = (ListNode*)malloc(sizeof(ListNode));    head->next = NULL;    head->val = 1;    temp = head;    for(i = 2; i < 6; i++)    {        newNode = (ListNode*)malloc(sizeof(ListNode));        newNode->next = NULL;        newNode->val = i;        temp->next = newNode;        temp = newNode;    }    temp = head;    while(temp)    {        cout << temp->val << "  " ;        temp = temp->next;    }    cout << endl;    head = s.ReverseList(head);    temp = head;    while(temp)    {        cout << temp->val << "  " ;        temp = temp->next;    }    cout << endl;    return 0;}
0 0
原创粉丝点击