题目1518:反转链表

来源:互联网 发布:seo h1标签 编辑:程序博客网 时间:2024/05/17 12:49
题目描述:

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

输入:

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

输出:

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

样例输入:
51 2 3 4 50
样例输出:
5 4 3 2 1NULL

 #include<stdio.h>#include<malloc.h>typedef struct Node{    int data;    struct Node *next;}LNode,*LinkList;int ListLength(LinkList L);int InitList(LinkList *L){    *L=(LinkList)malloc(sizeof(LNode));    if((*L) == NULL)        return 0;    (*L)->next = NULL;    return 1;}void DestroyList(LinkList *L){    LNode *p,*q;    p=(*L)->next;    while(p!=NULL)    {        q = p->next;        free(p);        p=q;    }    }int InsertLast(LinkList L,int data){    LNode *p,*q;    p=(LNode*)malloc(sizeof(LNode));    q=L;    while(q->next!=NULL)    {        q=q->next;    }    p->data = data;    q->next =p;    p->next =NULL;    return 1;}void Print(LinkList L){    int len=ListLength(L);    if(len == 0)    {        printf("NULL\n");        return ;    }    LNode *p=L->next;    while(p->next!=NULL)    {        printf("%d ",p->data);        p=p->next;    }    printf("%d\n",p->data);}int ListLength(LinkList L){    int cnt=0;    LNode *p=L->next;    while(p!=NULL)    {        cnt++;        p=p->next;    }    return cnt;}void GetElem(LinkList L,int i,int *e){    LNode *p=L->next;    int j=0;    while(j<i)    {        j++;        p=p->next;    }    *e = p->data;}int main(){    LinkList L,L1;    int n,t;    int e;    while(scanf("%d",&n)!=EOF)    {        InitList(&L);        InitList(&L1);        for(int i=0;i<n;i++)        {            scanf("%d",&t);            InsertLast(L,t);        }        for(int i=0;i<n;i++)        {            GetElem(L,n-i-1,&e);            InsertLast(L1,e);                }        Print(L1);        DestroyList(&L);        DestroyList(&L1);    }}
0 0
原创粉丝点击