剑指Offers 题目1511:从尾到头打印链表

     题目1511:从尾到头打印链表

             题解报告:方法一、链表创建,头插法,方法二、运用栈,注意栈可能溢出~!

         

#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
// stack
int main()
{
          int num;
         stack<int> List;
        while(scanf("%d", &num) && num !=-1){
 
             List.push(num);
 
         }
          while(!List.empty()){
           printf("%d\n", List.top());
           List.pop();
         }
 
       return 0;
}
 
/**************************************************************
    Problem: 1511
    User: qiu0130
    Language: C++
    Result: Accepted
    Time:80 ms
    Memory:1916 kb
****************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Lnode{
    int data;
    struct Lnode *next;
 
}Lnode;
 
// 头插法
int main()
{
         int num;
        Lnode *List = (Lnode *)malloc(sizeof(Lnode));
          List->data = 0;
          List->next=NULL;
        while(scanf("%d", &num)&&num!=-1){
                   Lnode *p= (Lnode *)malloc(sizeof(Lnode));
                   p->data = num;
                   p->next = List->next;
                   List->next = p;
 
 
         }
           Lnode *p = List->next;
           while(p != NULL){
             printf("%d\n", p->data);
                 p=p->next;
            }
 
       return 0;
}
 
/**************************************************************
    Problem: 1511
    User: qiu0130
    Language: C
    Result: Accepted
    Time:90 ms
    Memory:3948 kb
****************************************************************/

 

posted @ 2014-11-09 20:05  tt_tt--->  阅读(142)  评论(0编辑  收藏  举报