您的位置:首页 > Web前端

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

2015-09-05 00:03 441 查看
代码实现:

[code]#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: