九度 1518 :反转链表

题目来源:http://ac.jobdu.com/problem.php?pid=1518

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:1086

解决:457

题目描述:

输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:

对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1
NULL
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct Node
{
    int iData;
    Node* pNext;
    Node()
    {
        iData = 0;
        pNext = NULL;
    }
};

Node* pHead;

void Reverse_List()
{
    Node* p1 = pHead->pNext;
    Node* p2 = p1->pNext;
    p1->pNext = NULL;
    while(p2 != NULL)
    {
        Node* tmp = p2->pNext;
        p2->pNext =  p1;
        p1 = p2;
        p2 = tmp;
    }
    pHead->pNext = p1;
}

void Print_List()
{
    Node* p1 = pHead->pNext;
    while(p1->pNext != NULL)
    {
        printf("%d ", p1->iData);
        p1 = p1->pNext;
    }
    printf("%d\n", p1->iData);
}

void Delete_List()
{
    Node* p1 = pHead;
    Node* p2 = NULL;
    while(p1 != NULL)
    {
        p2 = p1->pNext;
        delete p1;
        p1 = p2;
    }
}

int main()
{
    int n, i;
    while(~scanf("%d", &n))
    {
        pHead = new Node();
        Node* p1 = pHead;
        Node* pNode = NULL;
        for(i = 0; i < n; ++i)
        {
            pNode = new Node();
            scanf("%d", &pNode->iData);
            p1->pNext = pNode;
            p1 = pNode;
        }
        if(pHead->pNext == NULL)
            printf("NULL\n");
        else if(n == 1)
            printf("%d\n", pHead->pNext->iData);
        else
        {
            Reverse_List();
            Print_List();
        }
        Delete_List();

    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值