题目1511:从尾到头打印链表
【代码】
- /*********************************
- * 日期:2013-10-18
- * 作者:SJF0115
- * 题号: 九度OJ 题目1511:从尾到头打印链表
- * 来源:http://ac.jobdu.com/problem.php?pid=1511
- * 结果:AC
- * 来源:剑指Offer
- * 总结:
- **********************************/
- #include<iostream>
- #include<malloc.h>
- #include<stdio.h>
- #include<stack>
- using namespace std;
- typedef struct ListNode{
- int value;
- struct ListNode *next;
- }ListNode;
- //从尾到头输出链表
- int ListReverse(ListNode *head){
- stack<int> stack;
- ListNode *p;
- p = head->next;
- //遍历链表,把每个节点数值添加到栈中
- while(p != NULL){
- stack.push(p->value);
- p = p->next;
- }
- //输出栈
- while(!stack.empty()){
- printf("%d\n",stack.top());
- stack.pop();
- }
- return 0;
- }
- int main()
- {
- int i,n;
- //初始化
- ListNode *head = (ListNode *)malloc(sizeof(ListNode));
- ListNode *p;
- head->next = NULL;
- p = head;
- while(scanf("%d",&n)!= EOF){
- //n = -1一个测试用例的结束
- if(n != -1){
- //创建链表
- ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
- newNode->value = n;
- newNode->next = p->next;
- p->next = newNode;
- p = newNode;
- }
- //输出
- else{
- /*p = head->next;
- while(p != NULL){
- printf("%d\n",p->value);
- p = p->next;
- }*/
- //从尾到头输出
- ListReverse(head);
- //初始化
- head->next = NULL;
- p = head;
- }
- }
- return 0;
- }
【解析】